I have such lifecycle hook
ponentDidUpdate(prevProps) {
// Typical usage (don't forget to pare props):
if (prevProps.activeItems !== this.props.activeItems) {
this.props.doAction();
}
}
and props have such a structure
[
{id:1, hidden: true},
{id:2, hidden: false}
{id:3, hidden: true}
]
I need to check if property hidden is the same in prev and next props for in every object, so I will know if I need to run function in if condition or no. How can I do that?
I have such lifecycle hook
ponentDidUpdate(prevProps) {
// Typical usage (don't forget to pare props):
if (prevProps.activeItems !== this.props.activeItems) {
this.props.doAction();
}
}
and props have such a structure
[
{id:1, hidden: true},
{id:2, hidden: false}
{id:3, hidden: true}
]
I need to check if property hidden is the same in prev and next props for in every object, so I will know if I need to run function in if condition or no. How can I do that?
Share Improve this question asked Oct 16, 2018 at 11:26 rick1rick1 9464 gold badges18 silver badges33 bronze badges 1-
You really can't, that is the bad part of an immutable data structure. You'll have to do the checking manually, I use
array.every
, for this – Akxe Commented Oct 16, 2018 at 11:35
4 Answers
Reset to default 7Don't use ponentWillReceiveProps -- this hook will be soon deprecated. ponentDidUpdate is the correct hook for what you need.
The problem is that the parison you're doing is a shallow parison -- i.e. it doesn't pare the nested values in the respective arrays.
The basic idea is that you should loop over both arrays and pared individual nested values -- here's more information about that: How to pare arrays in JavaScript?
You could also use something like's lodash's isEqual method to perform a deep parison between two arrays: https://lodash./docs/4.17.10#isEqual
Make use of ponentWillReceiveProps.
ponentWillReceiveProps (nextProps) {
if(nextProps.something !== this.props.soemthing) {
//write your statements
}
}
If you have array of object then You need to map through each object inside array by paring old props.
Parent ponent could take care of this to provide immutable activeItems
only in case activeItems
elements change.
Otherwise activeItems
arrays needs to be tested if they are shallowly equal, e.g. with repose
:
import { shallowEqual } from 'repose';
...
ponentDidUpdate(prevProps) {
if (shallowEqual(prevProps.activeItems, this.props.activeItems)) {
this.props.doAction();
}
}
you can use ponentWillReceiveProps for now. because it is getting deprecated soon
ponentWillReceiveProps (nextProps) {
if(nextProps.something === this.props.soemthing) {
// do your work
}
}