简体   繁体   English

区别,当可观察变量在mobx中的动作方法和简单函数内更新时?

[英]Difference, when observable variable is updated inside action method and plain function in mobx?

I am using MBOX for state management in ReactJS . 我正在使用MBOXReactJS中进行状态管理。

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. 我有时会在某些函数中更新可观察变量,然后重新渲染react组件,有时我会使用@action方法来更新可观察变量。

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. action也是transaction ,这意味着从动作中更改的可观察值派生的任何值将在action完成后重新计算。 If you don't wrap the function in an action , derived values might be calculated multiple times. 如果您不将函数包装在action ,则可能会多次计算派生值。

Example - Recalculation after action ( JS Bin ) 示例-行动后重新计算( 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 ) 示例-立即重新计算( 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>;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM