简体   繁体   English

如何异步地在商店构造函数上加载MobX数据?

[英]How to load MobX data on store constructor, asynchronously?

I'm trying to write a MobX store which loads data asychronously in the constructor. 我正在尝试编写一个MobX存储,该存储在构造函数中异步加载数据。 The problem is, when I try to update the @observable , it doesn't fire the changes, so the React component is never updated. 问题是,当我尝试更新@observable ,它不会触发更改,因此React组件永远不会更新。

That's the store (actually, the setTimeout is a server call): 那就是商店(实际上, setTimeout是服务器调用):

class MyStore {
  @observable isLoading = true;

  constructor() {
    setTimeout(() => {
      this.isLoading = false; // won't update the React component!
    }, 1000);
  }
}

This component blocks the app until the load is complete: 该组件将阻止应用程序,直到加载完成:

const MyComponent = ({store, children}) =>
  store.isLoading ?
    <div>Loading, please wait...</div> :
    children;

export default inject('store')(MyComponent);

How can I trigger the updates in the store constructor? 如何在商店构造函数中触发更新?

In the code provided your component is not marked as an observer, making it an observer should solve the problem. 在提供的代码中,您的组件未标记为观察者,使它成为观察者应该可以解决问题。 You can do it with @observer decorator provided by mobx-react package. 你可以做到这一点@observer提供装饰mobx-react包。

Notice that you should use observer before inject 请注意, 注入之前应使用观察者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM