Skip to content Skip to sidebar Skip to footer

Updating Component's State Using Props

I'm trying to update some component's state using received props in this manner: componentWillReceiveProps(nextProps) { if(nextProps.history.length <= 2) { this.setStat

Solution 1:

The lifecycle method componentWillReceiveProps is deprecated. You should use getDerivedStateFromProps

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

Solution 2:

You can either use componentDidUpdate() lifecycle method or the static getDerivedStateFromProps() method.

staticgetDerivedStateFromProps(props, state) {
    return ({
        history: props.history.length <= 2 ? props.history : state.history
    })
}

Or if you prefer:

componentDidUpdate(prevProps) {
    const { history } = this.props;
    if((prevProps.history !== history) && history.length <= 2) {
        this.setState({ history })
    }
}

Post a Comment for "Updating Component's State Using Props"