I am trying to upgrade my react version from react 15 to 16 so while doing that am facing one challenge in getDerivedStateFromProps . In ComponentWillReceiveProps ,
componentWillReceiveProps(nextProps) {
if (nextProps.postDetails !== []) {
this.setState({
postDetails: nextProps.postDetails
});
}
if (nextProps.userData.length === 2) {
this.setState({
userData: nextProps.userData
});
}
}
// in the above am checking two different props and setting the value accordingly
In getDerivedStateFromProps ,
static getDerivedStateFromProps(props, prevState) {
if (prevState.value !== props.value) {
return {
value: props.value
}
}
}
//here the problem is ,am unable to do multiple props validations here
my question here is , as i did in componentWillReceiveProps how to do multiple props validation in getderivedstatefromprops . Can someone clarify me on this .
I tried like this below, but it is not coming to next if !!!
let xx = true;
let yy = true;
if (xx) {
console.log("if 1");
return {
value: nextProps.someValues,
};
}
if (yy) {
console.log("if 2");
return {
value2: nextProps.someValues2,
};
}
expected o/p two console logs but am getting 1st if console only !!
You can pass as many props add you need into a component. you are passing the props to dump component. it's not react component. pass the props to dump as function argument.
There are a few life cycle methods that have been deprecated and renamed in React 17. We don't need to use these anymore— getDerivedStateFromProps and getSnapshotBeforeUpdate essentially replaced them.
ReactJS – getDerivedStateFromProps() MethodThis method is majorly used to update the state, before the rendering of the component, which depends upon the props received by the component. This method is called on every rerendering of the component.
3, getDerivedStateFromProps() was added as a static lifecycle method to prevent unsafe accesses of instance properties. getDerivedStateFromProps() is bound with null value when it is called by React. Therefore, when accessing this in the static lifecycle method, a TypeError exception is thrown.
just use intermediate variable to stack the changes
getDerivedStateFromProps(props, state) {
let update = {};
if (props.postDetails !== []) {
update.postDetails = props.postDetails;
}
if (props.userData && props.userData.length === 2) {
update.userData = props.userData;
}
return update;
}
As suggests @V-SHY it makes sense to ensure if we have at least one property me need to provide. Otherwise we better return null
to avoid unnecessary re-rendering.
return Object.keys(update).length ? update : null;
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