首页 > 解决方案 > 如何在 ES5 中实现 PureComponent

问题描述

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

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

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

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

有人对此有任何了解吗?

标签: ruby-on-railsreactjsecmascript-5react-rails

解决方案


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

推荐阅读