如何确定何时调用mobx计算变量?

时间:2020-05-11 09:12:29

标签: javascript reactjs mobx react-dom mobx-react

我一直在使用计算出的mobx,但是我无法理解以下代码正在发生什么:

import React, { Component } from "react";
import { render } from "react-dom";
import { observable, computed } from "mobx";
import { observer } from "mobx-react";

@observer
class Counter extends Component {
  @observable count = 0;
  @observable secondCount = 0;

  @computed
  get countString() {
    console.log("countString Computed");
    return `${this.count} ${this.secondCount}`;
  }

  onChangeCount = () => {
    this.count = this.count + 1;
    this.secondCount = this.secondCount + 1;
  };

  render() {
    console.log("render Counter");
    return (
      <div>
        <p>Count String: {this.countString}</p>
        <button onClick={this.onChangeCount}>Change count</button>
      </div>
    );
  }
}

render(<Counter />, document.getElementById("root"));

当用户按下更改计数btn时,输出为:

countString Computed 
render Counter 
countString Computed 
  • 在阅读mobx计算的fn文档之后,我了解到,如果我们不将@action应用于事件处理程序,则派生的fns(如计算的,自动运行的)将对每个状态突变执行一次反应。因此调用了两次计算。
  • 我的问题是,它们的调用顺序:

为什么不这样:

countString Computed 
countString Computed 
render Counter 

或类似这样:

render Counter 
countString Computed 
countString Computed 

总而言之,在上面的代码段中如何确定日志的执行顺序?

  • Mobx 5
  • 正在使用反应0.13.0

1 个答案:

答案 0 :(得分:0)

请参阅以下链接

Reaction order

Reaction order in v5

以上链接的摘要:

您不应该依赖副作用的执行顺序,因为它们在系统外部。