React replace componentWillReceiveProps

社会主义新天地 提交于 2020-08-10 13:08:47

问题


Having the following method in my child component which updates state on prop changes which works fine

  componentWillReceiveProps(nextProps) {
    // update original states
    this.setState({
      fields: nextProps.fields,
      containerClass: nextProps.containerClass
    });
  }

I'm getting Warning: Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code.

and I try to update but till now without any success

static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.fields !== prevState.fields) {
      return { fields: nextProps.fields };
    }
  }

  componentDidUpdate(nextProps) {
    console.log(nextProps);
    this.setState({
      fields: nextProps.fields,
      containerClass: nextProps.containerClass
    });
  }

because I get in infinite loop.

How do I update properly my state based in new props


回答1:


You get loop because you set new state every time component updates. So if state updates, that means component updates, and you update it again. Because of that, you need to prevent updating component on state change.

componentDidUpdate(prevProps, nextProps) {
  if(prevProps !== this.props){
   console.log(nextProps);
   this.setState({
     fields: nextProps.fields,
     containerClass: nextProps.containerClass
   });
 }
}



回答2:


You set the state, which will trigger another call and update which will call again and so on. You must check if the value is changing first, and then set the state.

componentDidUpdate(nextProps) {
    console.log(nextProps);
    if (nextProps.fields !== this.state.nextProps.fields){
        this.setState({
           fields: nextProps.fields,
           containerClass: nextProps.containerClass
        });
    }
  }

I recommended you to use hooks see here.




回答3:


I get there many times before.. All you need to do is to wrapp this.setState({.. in some coditional.

You have componentDidUpdate(prevProps, prevState, snapshot) so just compare if nextProps.fields and/or nextProps.containerClass are different than this.props.fields and this.props.containerClass - and only then set State

Btw, in CDM nextProps is actually prevProps



来源:https://stackoverflow.com/questions/60919347/react-replace-componentwillreceiveprops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!