简体   繁体   English

如何在 ES5 中实现 PureComponent

[英]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.一点上下文:Rails Application running react-rails on sprockets (No es6) React 版本 15.4.1。

This means our components are defined like: var ComponentName = React.createClass(...这意味着我们的组件定义如下: var ComponentName = React.createClass(...

I'm attempting to use a callback to pass state from a child component to a parent component.我正在尝试使用回调将 state 从子组件传递到父组件。 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.问题开始是因为父 state 的更新导致子组件重新渲染导致堆栈级别太深错误。

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.有人告诉我,我可以让子组件停止使用 PureComponent 重新渲染,但我还没有在 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. PureComponent 基本上只是一种自动执行shouldComponentUpdate的方法,它对 props 和 state 进行浅层比较。 While you can't use PureComponent with React.createClass, you can use shouldComponentUpdate.虽然您不能将 PureComponent 与 React.createClass 一起使用,但您可以使用 shouldComponentUpdate。 You could either implement your own comparison function, or use the one in react-addons-shallow-compare.您可以实现自己的比较 function,或者使用 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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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