2016-08-19 50 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