向此示例添加样式组件后,我们注意到,当仅修改状态中的一项时,我们的列表组件会更新所有内容。

添加/删除单个条目时,列表渲染亮点(来自 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 状态的已修改对象才会重新渲染?

请您参考如下方法:

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

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


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!