Reputation: 946
I have such lifecycle hook
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare 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?
Upvotes: 1
Views: 13326
Reputation: 81
you can use componentWillReceiveProps for now. because it is getting deprecated soon
componentWillReceiveProps (nextProps) {
if(nextProps.something === this.props.soemthing) {
// do your work
}
}
Upvotes: -1
Reputation: 222474
Parent component 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 recompose
:
import { shallowEqual } from 'recompose';
...
componentDidUpdate(prevProps) {
if (shallowEqual(prevProps.activeItems, this.props.activeItems)) {
this.props.doAction();
}
}
Upvotes: 0
Reputation: 349
Don't use componentWillReceiveProps -- this hook will be soon deprecated. componentDidUpdate is the correct hook for what you need.
The problem is that the comparison you're doing is a shallow comparison -- i.e. it doesn't compare the nested values in the respective arrays.
The basic idea is that you should loop over both arrays and compared individual nested values -- here's more information about that: How to compare arrays in JavaScript?
You could also use something like's lodash's isEqual method to perform a deep comparison between two arrays: https://lodash.com/docs/4.17.10#isEqual
Upvotes: 7
Reputation: 2023
Make use of componentWillReceiveProps.
componentWillReceiveProps (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 comparing old props.
Upvotes: 0