繁体   English   中英

如何在 ES5 中实现 PureComponent

[英]How to implement a PureComponent in ES5

一点上下文:Rails Application running react-rails on sprockets (No es6) React 版本 15.4.1。

这意味着我们的组件定义如下: var ComponentName = React.createClass(...

我正在尝试使用回调将 state 从子组件传递到父组件。 问题开始是因为父 state 的更新导致子组件重新渲染导致堆栈级别太深错误。

有人告诉我,我可以让子组件停止使用 PureComponent 重新渲染,但我还没有在 ES5 中找到实现。

有人对此有任何了解吗?

PureComponent 基本上只是一种自动执行shouldComponentUpdate的方法,它对 props 和 state 进行浅层比较。 虽然您不能将 PureComponent 与 React.createClass 一起使用,但您可以使用 shouldComponentUpdate。 您可以实现自己的比较 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