简体   繁体   中英

How to implement a PureComponent in ES5

A bit of context: Rails Application running react-rails on sprockets (No es6) React version 15.4.1.

This means our components are defined like: var ComponentName = React.createClass(...

I'm attempting to use a callback to pass state from a child component to a parent component. The problem begins because the updating of the parent state causes the child component to re-render resulting in a stack level too deep error.

I was told I could get the child component to stop re-rendering using a PureComponent but I have not found an implementation in ES5.

Does anyone have any light on this?

PureComponent is basically just a way to automatically do a shouldComponentUpdate that does a shallow comparison of the props and state. While you can't use PureComponent with React.createClass, you can use shouldComponentUpdate. You could either implement your own comparison function, or use the one in react-addons-shallow-compare.

var shallowCompare = require('react-addons-shallow-compare');

var Example = React.createClass({
  shouldComponentUpdate: function(nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState);
  },

  // rest of the component
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM