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

Cha*_*ith 7 reactjs react-dom styled-components

在为这个例子添加样式组件之后,我们注意到当我们只修改了一个状态项时,我们的列表组件会更新所有内容.

添加/删除单个条目时,列表呈现突出显示(来自React dev-tools)过多.删除/添加一个项目,然后突出显示所有项目.

在此输入图像描述

代码示例

以下是右侧列表组件(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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

偏爱

我更喜欢使用PureComponent,以便shouldComponentUpdate() 自动处理.

我们如何才能确保只items重新呈现状态中的修改对象?

Era*_*ran 1

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

一般来说,这将是您可以对纯组件重新渲染进行一些控制的方式: https://reactjs.org/docs/react-api.html#reactmemo