简体   繁体   中英

react component lifecycle componentWillRecieveProps

I am working on an application and when i had the ...this.state in my componentWillRecieveProps my code was not working correctly.

I am not 100% sure why this was affecting my state. Is it because i am always appending the current state when theres no need to do that.

componentWillReceiveProps(nextProps) {
   // this.setState({ ...this.state, ...nextProps })
    this.setState({...nextProps})
  }

The componentWillReceiveProps lifecycle function is deprecated. Please use the getDerivedStateFromProps static method instead. In your case it will look like this:

class Example extends React.Component {
  state = {
    ...
  }

  static getDerivedStateFromProps(nextProps) {
    return {...nextProps}
  }

  render() {
    ...
  }
}

However in real life it is aimless to convert every props to state without using any logic. In this case it is better to reach the props directly via this.props .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM