Mobx @obsevable XXX data has been modified, but the page does not render in real time.
You can print it in @Action. The value of @Observable XXX changes when you click on the button, but re-render is not triggered. I found a lot of documents, and the Github issue has been searched all over. The final solution was speechless.
Start with the error code
import { observable, action } from "mobx";
exportdefault class HomeStore { @observable num ; // Register variables to make them testableconstructor() { this.num = 0; } @action = () => {this.num += 1; console.log(this) }; @action minus = () => { this.num -= 1; }; }Copy the code
- Page code here on the subsidy, in simple terms is a page
<Text>{HomeStore.num}</Text>
And then keep clicking the button to trigger@action
The event - Console. log can be seen in browser debugging that num +1 is true, but the page is still 0
- … class = ‘class_constructor’ > store. Some people have given initial values, while others don’t. Then I’ll try removing the constructor initializer from @Observable num = 0, and there it is.
Success code
import { observable, action } from "mobx";
exportdefault class HomeStore { @observable num = 0 ; // Register variables to make them detectable @action // The recommended arrow function plus = () => {this.num += 1; console.log(this) }; @action minus = () => { this.num -= 1; }; }Copy the code
Success results are as follows, but note here!! Print this is different!!
- More than a Symbol!
Let’s go back to this after we gave the initial value from constructor
The contrast between the react component and the React component is obvious. With constructor, this pointer becomes a component of its own without mobx-related binding properties and functions. Observable Num = 0, num has mobx’s bidirectional data binding function. Change the data to refresh instantly!!
- Specific principle of my knowledge is not too shallow to understand clearly, which big guy know hope to be able to leave a message in the comment area AMD YES!