我开始学习mobx,我不明白为什么mobx发明了"动作"实体。将所有更改批量处理到setImmediate中的下一个tick会更容易吗?这将自动使所有同步状态更改的行为与@action现在一样。在行动结束后,而不是在下一个滴答声内,是否有利于触发观察者的权利?
答案 0 :(得分:0)
根据https://github.com/mobxjs/mobx/issues/1523的对话:
几个例子(所有jsx组件都应该在@observer
内):
// Ok to do this
<input value={appState.name} onChange={e => appState.name = e.target.value}/>
// Ok too, will rerender only once
<input value={appState.name} onChange={e => {
appState.name = e.target.value;
appState.foo = appState.foo + 1;
}}/>
// Not very good, will rerender twice on each click.
// Nevertheless, I do not know why someone will do this
<button onClick={() => {
setTimeout(() => {
appState.foo = appState.foo + 1;
appState.bar = appState.bar + 10;
}, 0);
}}>Click me foo={appState.foo} bar={appState.bar}</button>
// But that way it will rerender once and show console output only once too
autorun(() => console.info(`App state foo={appState.foo} bar={appState.bar}`));
<button onClick={() => {
setTimeout(() => {
runInAction(() => {
appState.bar = appState.bar + 10;
appState.foo = appState.foo + 1;
})
}, 0);
}}>Click me foo={appState.foo} bar={appState.bar}</button>
// That code will show console output twice, but rerender only once
autorun(() => console.info(`App state foo={appState.foo} bar={appState.bar}`));
<button onClick={() => {
setTimeout(() => {
ReactDOM.unstable_batchedUpdates(() => {
appState.bar = appState.bar + 10;
appState.foo = appState.foo + 1;
})
}, 0);
}}>Click me foo={appState.foo} bar={appState.bar}</button>