How to determine when mobx computed variable is called.?

倾然丶 夕夏残阳落幕 提交于 2020-05-28 04:45:26

问题


I have been playing with mobx computed, but I am having trouble understanding what is happening with the following code:

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");
    // console.log("count", this.count)
    // console.log("secondCount", this.secondCount)
    return (
      <div>
        <p>Count String: {this.countString}</p>
        <button onClick={this.onChangeCount}>Change count</button>
      </div>
    );
  }
}

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

When user presses the change count btn, the output is:

countString Computed 
render Counter 
countString Computed 
  • However, when I uncomment the two lines written inside the render fn of Counter component, the output changes
 // console.log("count", this.count)
 // console.log("secondCount", this.secondCount)
  • The output will be:
render Counter 
count 1
secondCount 1
countString Computed 

Why computed fn is being called only once when I dereference the observable variables inside render fn?

  • Mobx 5
  • React 0.13.0

来源:https://stackoverflow.com/questions/61726239/how-to-determine-when-mobx-computed-variable-is-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!