【问题标题】:MobX async reactionMobX 异步反应
【发布时间】:2016-12-26 11:18:13
【问题描述】:

您好,我在商店中使用 MobX,当计算值发生更改时,我需要进行异步响应:

class Store {
    @observable user;
    @observable something;

    @computed get firstParam () {
         return this.user && this.user.params[0];
    }

    async loadSomething () {
        reaction(
                () => this.firstParam,
                async (param) => {
                    const { data: something } = await axios.get(`url/${param}`);

                    runInAction('update state after fetching something', () => {
                        this.something = something;
                    });
                }
            );
     }

}

我想知道除了运行条件之外使用when 而不是reaction 有什么区别?

when(
    () => !!this.firstParam,
    async () => {
         // fetch using this.firstParam
    }
)

【问题讨论】:

  • 你是如何在你的机器上完成这项工作的?

标签: javascript asynchronous store mobx


【解决方案1】:

请注意,when 只会执行它的效果一次然后停止。所以在你的情况下,数据只会被提取一次。

【讨论】:

    【解决方案2】:
            reaction(
                () => this.firstParam,
                async (param) => {
                    const { data: something } = await axios.get(`url/${param}`);
    
                    runInAction('update state after fetching something', () => {
                        this.something = something;
                    });
                }
            );
    

    这将只跟踪this.firstParam,当它返回一个新数据时它会调用

                async (param) => {
                const { data: something } = await axios.get(`url/${param}`);
    
                runInAction('update state after fetching something', () => {
                    this.something = something;
                });
    

    现在,如果你选择when,我相信它最终也会这样做, 取自 mobx 文档:

    您可以使用可观察的数据结构作为一个承诺...完成异步操作后,只需更新您的数据

    所以我认为没有理由在你的情况下不使用when

    【讨论】:

      猜你喜欢
      • 2019-12-21
      • 2017-02-24
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 2020-09-27
      • 2021-07-22
      • 2018-05-27
      • 2021-02-06
      相关资源
      最近更新 更多