Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React props comparison: "_.isEqual" versus "==="

My issue is that lodash's deep comparison of equality and ==='s strict equality return different values when comparing fields of nextProps and self.props in the componentWillReceiveProps lifecycle method.

  1. Does this mean that the values of these properties must be of different types? I'm assuming _.isEqual does do type conversion to compare equality since === does not.
  2. Is it recommended to use _.isEqual when doing equality checking between fields of nextProps and self.props?

Here's my specific example -

componentWillReceiveProps(nextProps){
  (nextProps.obj === self.props.obj);        // false
   _.isEqual(nextProps.obj, self.props.obj); // true

   typeof(nextProps.obj);  // object
   typeof(self.props.obj); // object

   nextProps.obj;   // { k1: "v1", k2: "v2", k3: "v3" }
   self.props.obj;  // { k1: "v1", k2: "v2", k3: "v3" }
}

Does anyone know what might be going on?

like image 211
David Streid Avatar asked May 02 '18 02:05

David Streid


People also ask

How do you compare two objects in react?

Try using this function. const includesObject = (array = [], object = {}) => { const filteredArray = array. filter( (element) => JSON. stringify(element) === JSON.

Does react deep compare props?

If these contain complex data structures, it may produce false-negatives for deeper differences. React components don't compare props, unless they implement shouldComponentUpdate , like PureComponent . A component can be re-rendered with exactly same prop ( === equal).

How do you check if two values are equal in react?

With the === or the == operators -0 and +0 are treated as equal. The === operator also treat NaN and Number.


1 Answers

_.isEquals :

Performs a deep comparison between two values to determine if they are equivalent. it will return true if the values are equivalent, else false.

Lodash _.isEquals

Example:

var object = { 'a': 1 };
var other = { 'a': 1 };
 
console.log(_.isEqual(object, other));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

=== :

For strict equality the objects being compared must have the same type and:

compared must have the same type and:

  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
  • Two Boolean operands are strictly equal if both are true or both are false.
  • Two objects are strictly equal if they refer to the same Object

Comparison Operators - MDC

Example:

var object = { 'a': 1 };
var other = { 'a': 1 };
 
 
console.log(object === other);
// => false
like image 77
Harsh Patel Avatar answered Oct 11 '22 09:10

Harsh Patel