reactjs - React,避免重新渲染特定的子组件
问题描述
我有这个组件树:
Father
Son
Childrens
Daughter
Childrens2
Modal
每次 Modal 打开(通过设置this.setState({ openSimpleModal: true });
)或关闭(将状态设置为false
)时,组件 Son、Daughter 及其子组件都会重新渲染到。有没有办法可以打开和关闭模态,但不允许重新渲染 1 个特定组件,例如,Son
(及其子组件)但重新渲染其余部分?(女儿等)但仅在模态打开或关闭时。我需要在其他场景中渲染每个子组件,但是我需要在 Modal 打开/关闭时停止重新渲染
我尝试的是使用
shouldComponentUpdate(nextProps: Readonly<P>, nextState: Readonly<S>, nextContext: any): boolean {
return this.state.openSimpleModal === nextState.openSimpleModal
}
并确定模态的状态是否改变,在这种情况下返回 false,但它不起作用,因为模态当然不会显示。
解决方案
在您
shouldComponentUpdate
的情况下,当两者都相同时,您将返回 true,因此它会更新。所以应该是shouldComponentUpdate(nextProps: Readonly<P>, nextState: Readonly<S>, nextContext: any): boolean { return this.state.openSimpleModal != nextState.openSimpleModal }
- 如果不会导致任何性能问题,则无需关心重新渲染。
- 您可以根据您的要求使用 React.memo、React.PureComponent 或 React.useMemo
推荐阅读
- css - 使用 css 选择器在 img 之后选择 ::after
- c++ - 虽然循环没有中断??C++
- node.js - heroku 上的 WebSocket 连接问题:“WebSocket 在连接建立之前关闭”
- r - 在 R 中创建新列,仅在满足条件时将前一个值加 1
- password-protection - 存储密码的位置 - 第 3 方 API
- ios - 如何配置 SwiftUI openweathermap 应用程序以搜索包含多个单词的城市名称(例如纽约市)
- java - 无法在“/Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home/bin/apt”中找到可执行文件 (-1)
- python-3.x - Python模块Azure Identity 1.7.1中不需要的终端http请求输出
- c# - 如何使用 System.Text.Json 序列化文字 JSON 值?
- c# - 如何让我的程序说我离答案很近或很远,然后再次输入?C#