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
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
});
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With