拉風的咖菲貓
2018-12-20 18:23:43
怎么去理解mobx的 @computed @autorun 我有點琢磨不透麻煩各位指點一下
1 回答

動漫人物
TA貢獻1815條經(jīng)驗 獲得超10個贊
@computed 是為了優(yōu)化代碼邏輯。比如 component 中需要展示 price 以及 total 兩個信息。
不使用@computed的話,需要這么寫。
@observable count;
handleCountAdd() {
this.count += 1;
this.setState({ total: this.count * this.props.price });
}
假如使用了 @computed,就可以寫成
@observable count;
@computed get total() {
return this.count * this.props.price;
}
handleCountAdd() {
this.count += 1;
}
第二種方法明顯優(yōu)于第一種,因為 total 其實相當于是根據(jù) price 和 count 得到的,雖然它同樣控制著展示,但是作為 state 會顯得有些冗余。
@autorun 的使用頻次太少,我也沒有找到很好的 case 來解釋...
添加回答
舉報
0/150
提交
取消