如何在每个组件渲染之前更新React中的状态?

时间:2017-10-09 12:12:22

标签: reactjs

我有一个看起来像这样的React组件:

class MyComp extends Component {
    constructor(props) {
        super(props);

        this.state = {
            myObject: this.props.myObject,
        };

        this.updateState = this.updateState.bind(this);
    }

    componentWillMount() {
        this.updateState();
    }

    updateState() {
        // removed for brevity, doing some calculations here
        // based on some data that is stored in Redux and is 
        // passed here as props.

        this.setState({
            myObject: newObject
        });
    }

    render() {
        return (
            // removed for brevity, renders some HTML elements
        );
    }
}

MyComp.propTypes = {
    myObject: PropTypes.object.isRequired,
    // some other props
};

export default MyComp;

关键是我也在使用Redux,当在渲染的组件上单击某些按钮时,我会更新Redux中的某些状态,并且更新工作正常。然后基于更新的Redux状态,我想更新MyComp组件的状态,该组件最初将状态作为prop,但该对象不在Redux中维护,而是另一个状态组件,它作为道具传递给MyComp

我只想在每次渲染上面的组件之前更新状态。但这似乎不起作用。虽然我在Redux中的数据已经更新并且工作正常,但是这样调用componentWillMount来更新我的本地状态似乎不起作用。我观察到的是它只调用了我的updateState函数,在每次重新渲染时都没有调用它。有没有想过如何在每次渲染调用之前更新状态?

1 个答案:

答案 0 :(得分:2)

您可以使用:

componentWillReceiveProps(nextProps)

在安装过程中,React不会使用初始道具调用componentWillReceiveProps。如果某些组件的道具可能会更新,它只会调用此方法。调用this.setState通常不会触发componentWillReceiveProps

因此,您可以使用forceUpdate()重新呈现html。

您可以在此处获得更多详细信息:

https://reactjs.org/docs/react-component.html

constructor(props) {
    ....
    this.updateState = this.updateState.bind(this);
}

// this will be called when it receive props
componentWillReceiveProps(nextProps) {
    // you can also check props with current version
    // and set conditions to update state or not
    this.updateState();
}

updateState(){
    // removed for brevity, doing some calculations here
    // based on some data that is stored in Redux and is 
    // passed here as props.

    this.setState({
        myObject: newObject
    });
}