【问题标题】:Prevent Component/PureComponent with styled-components from re-rendering all items after state change防止带有 styled-components 的 Component/PureComponent 在状态更改后重新渲染所有项目
【发布时间】:2019-04-19 00:42:31
【问题描述】:

在这个例子中添加了 styled-components 之后,我们注意到我们的列表组件会在只有一个状态项被修改时更新所有内容。

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

代码示例

这里是右列表组件的示例(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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-24
    • 2021-11-24
    • 2020-01-02
    • 2023-01-28
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多