我正在使用 MBOX 在 ReactJS 中进行状态管理。
我有时会在某些函数中更新可观察变量,然后它也会重新渲染 react 组件,有时我会使用 @action
方法来更新可观察变量。
那么这两种场景有什么区别,对渲染有什么影响呢?
最佳答案
一个 action
也是一个 transaction
,这意味着从您在 action 中更改的 observables 派生的任何值都将在 action
完成。如果您不将函数包装在 action
中,派生值可能会计算多次。
示例 - 操作后重新计算 ( JS Bin )
@observer
class App extends Component {
@observable x = 'a';
@observable y = 'b';
@computed get z() {
console.log('computing z...');
return `${this.x} ${this.y}`;
}
onClick = action(() => {
this.x = 'c';
this.y = 'd';
});
render() {
return <div onClick={this.onClick}> {this.z} </div>;
}
}
示例 - 立即重新计算 ( JS Bin )
@observer
class App extends Component {
@observable x = 'a';
@observable y = 'b';
@computed get z() {
console.log('computing z...');
return `${this.x} ${this.y}`;
}
onClick = () => {
this.x = 'c';
this.y = 'd';
};
render() {
return <div onClick={this.onClick}> {this.z} </div>;
}
}
关于javascript - 差异,当可观察变量在 mobx 中的 Action 方法和普通函数内更新时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44298936/