I am confused why in component as bellows, this.state is automatically changed when corresponding store updated?
The compoenent is listening to MyStore. Once the number there changed, it will call onchange()
in the component, which is supposed to get the new number from store by calling this.getStateFromStores()
. It works. However, my question is: I added this line const alreadyHasNewData = this.state;
to check this.state
before getStateFromStores()
.
Debug found that this.state
is already updated in sync with store, how come this could happen?
Any help thanks!
class My-component {
constructor() {
super();
this.state = this.getStateFromStores(); // default number is 8;
}
private userClicked() => void = () => {
int newNumber = 9;
MyActionCreators.userClicked(newNumber);
};
private onChange: () => void = () => {
// Why this.state is already has new number in store, which is 9?
const alreadyHasNewData = this.state;
// I think only this line will get updated number in store, which is 9.
const data = this.getStateFromStores();
this.setState({
weekMeetingCardData: data.weekMeetingCardData
});
}
componentDidMount(): void {
MyStore.addListener(this.onChange);
}
componentWillUnmount(): void {
MyStore.removeListener(this.onChange);
}
protected getStateFromStores() {
return {
MyStore.getNumber();
}
}
}