簡體   English   中英

Mobx 計算不起作用

[英]Mobx computed doesn't work

我正在使用 mobx 4.2.0 當我嘗試使用計算屬性時,我遇到了一些問題代碼,如下所示:

 class ODOM { constructor(props) { console.log('how many times') } @observable speed = 0 @action change(obj) { console.log(obj) Object.keys(obj).forEach(item => { this[item] = obj[item] }) } @computed get velocity() { console.log('entry') return this.speed*60*60/1000 } } const model = new ODOM() let total = 0 setInterval(() => { model.change({ speed: ++total }) }, 3000) export default model

控制台“入口”只運行一次這些代碼有什么問題

必須觀察您的計算,以便在它所依賴的可觀察量發生變化時重新計算它。

此示例使用自動運行來顯示行為:

class ODOM {
  @observable speed = 0

  @action change(obj) {
    Object.keys(obj).forEach(item => {
      this[item] = obj[item]
    })
  }

  @computed get velocity() {
    console.log('entry')
    return this.speed*60*60/1000
  }
}

const model = new ODOM()
let total = 0
setInterval(() => {
  model.change({
    speed: ++total
  })
}, 1000);

autorun(() => {
  console.log(model.velocity);
});

計算重新計算僅由組件中的 mobx 觸發,這些組件直接在 render 函數中使用此屬性,並且這些 react 組件必須使用@observer屬性進行注釋。

否則使用非計算/正常屬性或自己緩存值。

如果@withRouter 在@observer 下會使@observer,@computed 失敗像這樣(錯誤):

@observer 
// @ts-ignore
@withRouter

你需要這樣寫(正確):

// @ts-ignore 
@withRouter
@observer 

我發現了問題。因為觀察者沒有正確使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM