使用 mobx-persist 和 AsyncStore 持久化数据

Persist data with mobx-persist and AsyncStore

我正在尝试使用 AsyncStorage ('@react-native-community/async-storage') 持久性使用 mobx-persist。我的实现基本上是这样的:https://github.com/pinqy520/mobx-persist。我可以看到我的商店水合(在商店本身的构造函数中)。我也可以在我的组件中访问我的商店,但在应用程序启动之间不会保留任何更改。 mobx-persist 甚至适合吗?我错过了什么?文档是琐碎的、糟糕的和过时的,以及相应的示例(对于任何 react-* 来说似乎都是非常典型的)。

更新:刚刚注意到它在 componentDidMount 中读取失败。看起来商店稍后会在 componentDidMount 中被水化。知道为什么吗?

原来商店后来确实补水了。我已经添加商店 属性 以指示水合作用完成(注意我不坚持它):

  @observable hydrated = false;

  constructor() {
    hydrate('myStore', this).then(() => {
      this.hydrated = true;
    });
  }

然后在我的组件中,我开始听 hydration finish:

    when(
      () => this.props.observableStore.hydrated,
      () => this.doSomething(),
    );

然而,以上内容还不足以让它发挥作用。我还必须添加另一个 babel 插件,这样 react-native/decorators/Flow 就不会相互混淆——这实际上是我解决方案的关键:

["@babel/plugin-proposal-class-properties", { "loose": true}]