ReactJS: Check props and state on shouldComponentUpdate

时光总嘲笑我的痴心妄想 提交于 2019-12-10 15:22:30

问题


I want to check all properties and state if they are changed, return true if any changed and make a base component for all my root components.

I'm wondering if it won't be the best practice and make my components slow. Also, what I did always returns true:

shouldComponentUpdate: function(newProps, newState) {
    if (newState == this.state && this.props == newProps) {
        console.log('false');
        return false;
    }
    console.log('true');
    return true;
},
  1. Is there anything wrong with my code?
  2. Should I check for every variable inside props and state?
  3. Won't check for objects inside them make it slow depending on their size?

回答1:


It is considered best practice to compare props and state in shouldComponentUpdate to determine whether or not you should re-render your component.

As for why it's always evaluating to true, I believe your if statement isn't performing a deep object comparison and is registering your previous and current props and state as different objects.

I don't know why you want to check every field in both objects anyway because React won't even try to re-render the component if the props or state hasn't changed so the very fact the shouldComponentUpdate method was called means something MUST have changed. shouldComponentUpdate is much better implemented to check maybe a few props or state for changes and decide whether to re-render based on that.




回答2:


I think there's a problem in most of the tutorials I've seen (including the official docs) in the way that stores are accessed. Usually what I see is something like this:

// MyStore.js

var _data = {};

var MyStore = merge(EventEmitter.prototype, {

  get: function() {
    return _data;
  },

  ...

});

When I used this pattern, I found that the newProps and newState in functions like shouldComponentUpdate always evaluate as equal to this.props and this.state. I think the reason is that the store is returning a direct reference to its mutable _data object.

In my case the problem was solved by returning a copy of _data rather than the object itself, like so:

  get: function() {
    return JSON.parse(JSON.stringify(_data));
  },

So I'd say check your stores and make sure you're not returning any direct references to their private data object.




回答3:


There is a helper function to do the comparison efficiently.

var shallowCompare = require('react-addons-shallow-compare');
export class SampleComponent extends React.Component {
  shouldComponentUpdate(nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState);
  }

  render() {
    return <div className={this.props.className}>foo</div>;
  }
}


来源:https://stackoverflow.com/questions/28353702/reactjs-check-props-and-state-on-shouldcomponentupdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!