防止带有样式组件的Component / PureComponent在状态更改后重新呈现所有项目

时间:2018-11-15 20:31:45

标签: reactjs styled-components react-dom

在此示例中添加了样式化组件之后,我们注意到,只有状态中的一项被修改时,列表组件才会更新所有内容。

添加/删除单个条目时,列表渲染突出显示(来自React开发工具)过多。一项被删除/添加,然后所有项都突出显示。

enter image description here

代码示例

这是右列表组件(CategorizedList.js)的示例

VARCHAR(1023)

首选项

我希望使用PureComponent,以便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> ); } } gets handled automatically

问题

我们如何确保仅渲染处于shouldComponentUpdate()状态的已修改对象?

1 个答案:

答案 0 :(得分:1)

如果数据更改,则视图将重新呈现。这不应该是一个昂贵的过程,因为它在添加/删除操作中发生一次。如果发现性能问题,则可能是由其他原因引起的。

通常,这是您可以控制纯组件重新渲染的方式: https://reactjs.org/docs/react-api.html#reactmemo