本地状态未在Redux状态更新时更新

时间:2018-07-30 09:59:53

标签: reactjs redux

嗨,我有一个组件,可以将其本地状态从redux状态更新为

constructor(props){
        super(props);
        this.updatePanelInTemplate = this.updatePanelInTemplate.bind(this);
        this.getPanels = this.getPanels.bind(this);
        this.state = {
            myCustomTemplate: this.props.myCustomTemplate
        }
        console.log(this.state);
    }

const mapStateToProps = (state) => {
    console.log(state);
    return {
        resumeTemplate: state.resume.resumeTemplate,
        components: state.resume.components,
        myCustomTemplate: state.resume.myCustomTemplate
    }
}

这些是我所涉及的部分代码。我正在生命周期挂钩componentDidUpdate()

中更新redux状态

我的Redux很好地显示了更改。 我在每个控制台中都放置了一个控制台。 它按以下顺序打印

console--mapState // empty state
console--constructor // empty state
console--mapState// full state after update

但是此更新后,我的本地状态未反映任何更改。我不知道为什么。请再提及其他要求。

1 个答案:

答案 0 :(得分:2)

尝试这个

constructor(props){
    super(props);
    this.updatePanelInTemplate = this.updatePanelInTemplate.bind(this);
    this.getPanels = this.getPanels.bind(this);
    this.state = {
        myCustomTemplate: this.props.myCustomTemplate
    }
    console.log(this.state);
}

componentWillReceiveProps(nextProps) {
    const { myCustomTemplate } = nextProps;
    if (myCustomTemplate !== this.state.myCustomTemplate) {
        this.setState({
            ...this.state,
            myCustomTemplate,
        }, () => {
            console.log(this.state);
        })
    }
}

const mapStateToProps = (state) => {
    console.log(state);
    return {
        resumeTemplate: state.resume.resumeTemplate,
        components: state.resume.components,
        myCustomTemplate: state.resume.myCustomTemplate
    }
}