首页 文章

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

提问于
浏览
0

我有一个看起来像这样的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 回答

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

相关问题