Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React replace componentWillReceiveProps

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

like image 476
fefe Avatar asked Dec 22 '22 18:12

fefe


2 Answers

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
   });
 }
}
like image 104
Shotiko Topchishvili Avatar answered Jan 04 '23 17:01

Shotiko Topchishvili


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.

like image 37
M.M.J Avatar answered Jan 04 '23 17:01

M.M.J