3

In my react shouldComponentUpdate function,this.props and nextprops have all the same attributes, but they are not equal.My code:

shouldComponentUpdate(nextProps) {
    console.log(this.props);
    console.log(nextProps);
    console.log('nextProps vs this.props:', nextProps === this.props);
    console.log('this.props.style vs nextProps.style:', this.props.style === nextProps.style);
    console.log('this.props.data vs nextProps.data',this.props.data === nextProps.data);
    return true;
  }

the output is : enter image description here

My confusion is whether the props has some hidden attributes.

sunt
  • 479
  • 1
  • 5
  • 15

2 Answers2

0

Object comparison doesn't work that way.

For example take the following code:

test_a = {key: 'value'}
test_b = {key: 'value'}
console.log(test_a == test_b) //false

There are many ways to properly compare js objects for equality by value, and someone in the comment section has already provided a link to a previous thread on the topic.

Jake Haller-Roby
  • 6,335
  • 1
  • 18
  • 31
  • I know how to compare two object,but in the situation the focus is on the `react shouldComponentUpdate function` which is import to the render performance.If every attributes are equal, then the `this.props` and the `nextprops ` should be equal, then it will not rerender. – sunt Jul 25 '17 at 08:35
  • "If every attributes are equal, then the this.props and the nextprops should be equal,": That is not true. Look at my answer again. Comparing objects checks to see if they are occupying the same memory address, not whether their attributes are the same. – Jake Haller-Roby Jul 27 '17 at 18:08
  • What you mean is correct, wheather two objects are equal is determined by the memory address. But in the situlation `react` shuold not generate new props when no prop attributes had changed,I don't know why.`https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate` – sunt Jul 28 '17 at 01:31
-2

Just do a JSON.stringify(this.props) === JSON.stringify(nextProps)

  • 1
    https://reactjs.org/docs/react-component.html#shouldcomponentupdate We do not recommend doing deep equality checks or using JSON.stringify() in shouldComponentUpdate(). It is very inefficient and will harm performance. – аlex Nov 22 '18 at 16:21