简体   繁体   English

React shouldComponentUpdate() = false 不停止重新渲染

[英]React shouldComponentUpdate() = false not stopping re-render

Basically, I've got this pretty simple react component.基本上,我有这个非常简单的反应组件。 What it does is, is wrap around 'react-intercom' and only render it if there is a change in the state.它的作用是围绕“react-intercom”,并且仅在状态发生变化时才呈现它。 To simplify the question, I've hardwired the shouldCompoenentUpdate() method to always return false.为了简化问题,我将shouldCompoenentUpdate()方法硬连线以始终返回 false。

 import React from 'react'; import Intercom from 'react-intercom'; class IntercomWrapper extends React.Component { shouldComponentUpdate(nextProps, nextState) { // console.log(!!nextProps.user && nextProps.user.userId !== this.props.user.userId); // return !!nextProps.user && nextProps.user.userId !== this.props.user.userId; return false; } render() { console.log('rendering'); return <Intercom {...this.props} />; } }; export default IntercomWrapper;

What happens is that it always rerenders, which should not happen.发生的事情是它总是重新渲染,这不应该发生。

Anyone has any idea why would that happen?任何人都知道为什么会发生这种情况?

我最终想通了:问题是包装组件正在接收状态更改,并且正在无条件地重新渲染所有子项(这是正常行为。这是重新排列组件的问题(从我的<Layout>组件中取出这个 Intercom 包装器) .谢谢大家的帮助!干杯!

According to the docs , simply returning false does not stop rerendering. 根据文档 ,简单地返回false并不会停止重新渲染。 Reading this will show you how to do it properly. 阅读本文将向您展示如何正确地完成它。

More Information 更多信息

This wont prevent rendering of child components:这不会阻止渲染子组件:
From the DOCS :文档

Returning false does not prevent child components from re-rendering when their state changes.返回 false 不会阻止子组件在状态更改时重新渲染。 ... ...

Note that in the future React may treat shouldComponentUpdate() as a hint rather than a strict directive, and returning false may still result in a re-rendering of the component.请注意,将来 React 可能会将 shouldComponentUpdate() 视为提示而不是严格指令,并且返回 false 可能仍会导致重新渲染组件。

If Intercom component renders when IntercomWrapper does not (because of shouldComponentUpdate being set to false), that means that Intercom component listens to data changes independently from {...this.props} passed from its parent (for example, it can be subscribed to a store).如果 Intercom 组件在 IntercomWrapper 未呈现时呈现(因为 shouldComponentUpdate 设置为 false),则意味着 Intercom 组件侦听独立于从其父级传递的 {...this.props} 的数据更改(例如,它可以订阅一家商店)。

I had the same problem, Child component was rendering when its Parent was not because of shouldComponentUpdate set to false.我有同样的问题,当它的父组件不是因为 shouldComponentUpdate 设置为 false 时,子组件正在渲染。 The reason was - Child was subscribed to store and listened to data changes independently from a parent.原因是 - 孩子订阅了独立于父母的存储和监听数据更改。

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

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