React replace componentWillReceiveProps
Asked Answered
J

3

6

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

Joinder answered 29/3, 2020 at 19:3 Comment(0)
S
10

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
   });
 }
}
Submergible answered 29/3, 2020 at 19:18 Comment(1)
By React doc, the second parameter is prevState. So, componentDidUpdate(prevProps, prevState, snapshot). I think you might review your logicCurtsy
J
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.

Jonniejonny answered 29/3, 2020 at 19:16 Comment(0)
A
0

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

Anthropomorphosis answered 29/3, 2020 at 19:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.