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

问题描述 投票:0回答:1

我一直在使用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
javascript reactjs mobx react-dom mobx-react
1个回答
0
投票

请参阅以下链接

Reaction order in v5

© www.soinside.com 2019 - 2024. All rights reserved.