
1 noe132 Mar 9, 2020 via Android 0 * 1 不等 0 么? |
理解错了。。 |
3 ddzy Mar 9, 2020 没看懂 |
4 kuanng OP @ddzy 照我的理解:total 是一个 computed,它依赖于 price 和 amount。所以在 price 和 amount 没有改变下,total 的计算值被缓存起来,这样的话控制台不应该打印三次的 ff |
5 noe132 Mar 9, 2020 这个缓存只会在 when / autorun / reaction / 其他 computed 中被使用。 const state = observable({ a:1, b:2, c:3, get d(){ console.log('computed'); return this.a * this.b } }) m.reaction(() => temp3.c + temp3.d, () => { console.log('reaction')}) state.a = 3 // log reaction + run state.c = 5 // log reaction |
6 noe132 Mar 9, 2020 https://mobx.js.org/refguide/computed-decorator.html that if you create a computed property but don't use it anywhere in a reaction, it will not cache its value and recompute more often than seems necessary when / autorun / reaction 会假设你的依赖是除了包含 reactive 值的其他部分是不包含任何副作用的,所以会缓存,而在这些之外手动访问,可能不能保证不产生副作用。类似如果写出像这样的 getter: get d() { return [Date.now()] } 是否每次时间变化都会触发 autorun ?结果显然是不会,因为 Date.now()并不是 reactive 的。而 get d() 却并不是一个纯函数。 如果希望函数执行的结果每次都能缓存下来,需要自己封装一层,通过 reaction 将结果缓存下来,类似下面这样 const useMobxMemo = (computedFunction) => { const value = computed(computedFunction); const state = { value, }; reaction(() => value.value, () => { state.value = value.value; }); return state.value; }; |
7 momocraft Mar 9, 2020 class + decorator 的写法应该会缓存的 observable.object 会自动把 getter 转为 computed 吗? |