2016-08-19 51 views
2

嗨,我在商店使用MobX,我需要有一个异步反应时计算出的值已经改变: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 
    } 
) 

回答

5

请注意,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