【问题标题】:How to implement a PureComponent in ES5如何在 ES5 中实现 PureComponent
【发布时间】:2020-07-29 14:52:36
【问题描述】:

一点上下文:Rails 应用程序在 sprockets 上运行 react-rails(没有 es6)React 版本 15.4.1。

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

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

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

有人对此有所了解吗?

【问题讨论】:

  • 你是在使用旧的React.createClass 制作组件的方式吗?
  • 是的。我们正在使用它。

标签: ruby-on-rails reactjs ecmascript-5 react-rails


【解决方案1】:

PureComponent 基本上只是一种自动执行shouldComponentUpdate 的方法,它对道具和状态进行浅层比较。虽然您不能将 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
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    相关资源
    最近更新 更多