【问题标题】:Why React.memo and shouldComponentUpdate aren't doing the same?为什么 React.memo 和 shouldComponentUpdate 不一样?
【发布时间】:2019-07-08 16:29:27
【问题描述】:

我有一个功能组件,它与我的 Redux 存储中的对象有连接。为了避免在对象更改时重新渲染,我添加了React.memo,但是,这并没有避免重新渲染。我的备忘录看起来像这样:

const MemoizedRadio = React.memo(Radio, (prevProps, nextProps) => {
  if (prevProps.selected !== nextProps.selected) {
    return false;
  }
  return true;
});

const mapStateToProps = state => ({
  nodes: state.canvas.elements.nodes
});

export default connect(mapStateToProps)(MemoizedRadio);

如果nodes 对象已更改,我希望此组件不会重新渲染,但确实如此。

当我将组件重写为类组件并添加 shouldComponentUpdate 时,将按预期阻止重新渲染。 shouldComponentUpdate 如下所示:

shouldComponentUpdate(nextProps) {
    if (this.props.selected !== nextProps.selected) {
      return true;
    }
    return false;
  }

我认为React.memo 的行为与shouldComponentUpdate 相同,但事实并非如此。当nodes 对象的引用发生更改时,React.memo 实现总是会重新渲染,而shouldComponentUpdate 实现会按预期阻止重新渲染。

谁能解释这种行为?

【问题讨论】:

  • 快速提示:return prevProps.selected !== nextProps.selected 已经是布尔值了!
  • 嗯,这一切看起来都很好,为什么 selected 不是道具的一部分?另外,只是出于好奇,但为什么你会将nodes 作为道具传递,但如果它们发生变化,却对重新渲染不感兴趣?
  • @James 这只是为了展示一些简单的示例代码。我正在渲染一个包含很多节点的画布。每个节点也可以有子节点,它们是不同的节点。该节点有一个子属性,它只是子节点的 id。因此,要填充 childNode 中的内容,我需要访问所有节点并使用正确的值填充内容。

标签: javascript reactjs react-hooks


【解决方案1】:

您正确使用React.memo,问题是您使用connect HOC 将基于类的组件连接到商店。你应该使用 useDispatchuseSelector 而不是使用 HOC

【讨论】:

  • 谢谢!我将升级 react-redux 以使其与钩子一起使用,看看是否有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 2022-08-07
  • 2012-04-03
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多