问题
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