为什么在反应通量:组件this.state在商店更改时自动更新?

时间:2016-04-22 19:44:48

标签: reactjs state store flux refluxjs

我很困惑为什么在组件中作为风箱,当对应的商店更新时,this.state会自动更改?

该组件正在收听MyStore。一旦数字发生变化,它将在组件中调用onchange(),该组件应该通过调用this.getStateFromStores()从商店获取新号码。有用。不过,我的问题是:我在const alreadyHasNewData = this.state;之前添加了这一行this.state以检查getStateFromStores()
调试发现this.state已经与商店同步更新,为什么会发生这种情况?

任何帮助谢谢!

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();
        }
    }
}

0 个答案:

没有答案