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
});
}
}