1

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();
        }
    }
}
wintvelt
  • 13,855
  • 3
  • 38
  • 43
Ying
  • 11
  • 2
  • This code looks fine. Which debugger did you use to check the numbers? If unsure, maybe using `console.log()` will help. NB: make sure you debug or log the number, NOT the object. – wintvelt Apr 22 '16 at 19:54
  • I used chrome to debug, and I do debug by inspect number real stored in it. My confusion is: why in onChange() method, this.state is already updated to store's new number without calling this.getStateFromStores()? – Ying Apr 22 '16 at 23:38
  • In chrome, if you `console.log()` an object (such as `this.state`), you can inspect the contents of the object in the console, but the contents DO NOT necessarily give you the values at the time of logging. In your `console.log(...)`, what do you have in the `...`? – wintvelt Apr 23 '16 at 08:13

0 Answers0