向此示例添加样式组件后,我们注意到,当仅修改状态中的一项时,我们的列表组件会更新所有内容。
添加/删除单个条目时,列表渲染亮点(来自 React 开发工具)过多。删除/添加一项,然后所有项目都会突出显示。
代码示例
- github:https://github.com/chancesmith/reactjs-optimize-list-updates/tree/master/src
- 代码沙箱:https://codesandbox.io/s/wn45qw44z5
这是右侧列表组件 (CategorizedList.js) 的示例
import styled from "styled-components";
const Item = styled.li`
color: #444;
`;
class CategorizedList extends PureComponent {
render() {
return (
<div>
{this.props.categories.map(category => (
<ul>
<li key={this.props.catStrings[category]}>
{this.props.catStrings[category]}
</li>
<ul>
{this.props.items.map((item, index) =>
item.category === category ? (
<div key={item.label + index}>
<Item>{item.label}</Item>
</div>
) : null
)}
</ul>
</ul>
))}
</div>
);
}
}
偏好
我更喜欢使用 PureComponent,以便 shouldComponentUpdate()
gets handled automatically .
问题
我们如何确保只有处于 items
状态的已修改对象才会重新渲染?
最佳答案
如果数据发生变化, View 将重新渲染。它不应该是一个昂贵的过程,因为它在添加/删除操作时发生一次。如果您发现性能问题,可能是由其他原因引起的。
一般来说,这将是您可以对纯组件重新渲染进行一些控制的方式: https://reactjs.org/docs/react-api.html#reactmemo
关于reactjs - 防止带有样式组件的 Component/PureComponent 在状态更改后重新渲染所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53327479/