【发布时间】:2019-04-19 00:42:31
【问题描述】:
在这个例子中添加了 styled-components 之后,我们注意到我们的列表组件会在只有一个状态项被修改时更新所有内容。
添加/删除单个条目时,列表渲染亮点(来自 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状态的修改对象被重新渲染?
【问题讨论】:
-
根据您的链接
doing a check on their props and state is lightning fast compared to the cost of re-rendering each one您希望在该列表中采取什么样的性能影响到您需要采用这种方法的地方?
标签: reactjs styled-components react-dom