I am using MBOX for state management in ReactJS .
I sometime update observable variable inside some function, than also it re-render the react component and sometime i use @action
method to update the observable variable.
So what it is the difference between the two scenarios and what effect it will have on rendering?
An action
is also a transaction
, which means that any value that is derived from the observables you change in the action will be recalculated after the action
is finished. If you don't wrap the function in an action
, derived values might be calculated multiple times.
Example - Recalculation after 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>;
}
}
Example - Recalculation straight away ( 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>;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.