MobX 是一个流行的状态管理库,用于简化 React 应用程序中的状态管理。它通过响应式编程模型,使得状态的变化能够自动地反映在 UI 上。MobX 提供了多种反应性机制,其中之一就是 reaction
。
Reaction 是 MobX 中的一个核心概念,它允许你在状态变化时执行副作用操作。具体来说,reaction
会在其依赖的状态发生变化时自动重新运行指定的函数。
reaction
是一个函数,接受两个参数:一个数据获取函数和一个副作用函数。以下是一个简单的 reaction
使用示例:
import { observable, reaction } from 'mobx';
import { observer } from 'mobx-react';
class Store {
@observable count = 0;
constructor() {
reaction(
() => this.count, // 数据获取函数
(count, previousCount) => {
console.log(`Count changed from ${previousCount} to ${count}`);
// 这里可以执行任何副作用操作,比如更新数据库或发送网络请求
}
);
}
increment() {
this.count++;
}
}
const store = new Store();
const Counter = observer(({ store }) => (
<div>
<h1>{store.count}</h1>
<button onClick={() => store.increment()}>Increment</button>
</div>
));
// 在 React 组件中使用
ReactDOM.render(<Counter store={store} />, document.getElementById('root'));
问题:reaction
没有按预期触发。
原因:
@observable
:确保所有被观察的状态都使用了 @observable
装饰器。reaction
不会触发。解决方法:
通过以上方法,可以有效利用 MobX 的 reaction
功能来简化应用的状态管理和副作用处理。
领取专属 10元无门槛券
手把手带您无忧上云