【问题标题】:MobX observer does not react on observable changeMobX 观察者不会对可观察到的变化做出反应
【发布时间】:2021-07-13 19:31:48
【问题描述】:

这是我的观察:

class AppState implements IAppState {
  private static instance: AppState;
  public static getInstance(): AppState {
    if (!AppState.instance) {
      AppState.instance = new AppState(AppState.initState);
    }

    return AppState.instance;
  }

  static initState: IState = {
    isLoading: true,
    isSignedIn: false,
  };
  private appState: IState;

  private constructor(state: IState = AppState.initState) {
    makeAutoObservable(this);
    this.appState = state;
  }

  set isLoading(isLoading: boolean) {
    runInAction(() => (this.appState.isLoading = isLoading));
  }

  set isSignedIn(isSignedIn: boolean) {
    runInAction(() => (this.appState.isSignedIn = isSignedIn));
  }

  get state() {
    return this.appState;
  }
}

我在这里观察它:

const StackNavigator = observer(() => {
  return (
    <Stack.Navigator
      screenOptions={{
        headerShown: false,
        gestureEnabled: false,
      }}
    >
      {!AppState.state.isSignedIn ? (
        <>
          <Stack.Screen name="Login" component={WelcomeScreen} />
          <Stack.Screen name="Signup" component={SignUpVM} />
        </>
      ) : (
        <>
          <Stack.Screen name="Main" component={MainScreen} />
        </>
      )}
    </Stack.Navigator>
  );
});

但是当AppState.state.isSignedIn 更改时,不会发生重新渲染。可能是什么原因?可能与我在 React Navigation 组件上使用 observable 而不是自定义组件有关吗?任何帮助将不胜感激。

【问题讨论】:

    标签: mobx mobx-react


    【解决方案1】:

    尝试在构造函数中改变顺序:

      private constructor(state: IState = AppState.initState) {
        this.appState = state;
        makeAutoObservable(this);
      }
    

    来自docs

    make(Auto)Observable 仅支持已定义的属性。确保您的编译器配置正确,或者作为解决方法,在使用 make(Auto)Observable 之前为所有属性分配一个值。如果没有正确的配置,声明但未初始化的字段(如在 class X { y; } 中)将不会被正确拾取。

    【讨论】:

      猜你喜欢
      • 2018-07-28
      • 2018-01-22
      • 1970-01-01
      • 2019-03-19
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 2014-03-24
      • 2020-08-24
      相关资源
      最近更新 更多