简体   繁体   English

Redux状态更新导致React组件不必要地呈现

[英]Redux state update causing React component to render unnecessarily

I'm experiencing a few performance issues in my react / redux app. 我在react / redux应用程序中遇到一些性能问题。

I'm working with an object in one of my reducers which is quite deep. 我正在使用我的一个减速器中的一个对象,该对象很深。 It contains an object named list which holds a collection of objects. 它包含一个名为list的对象,其中包含对象的集合。

const state = {
  list: {
    one: {
      id: 'one',
      name: 'One',
      active: false
    },
    two: {
      id: 'two',
      name: 'Two',
      active: false
    }
  }
}

Each item in the object is used to render a component. 对象中的每个项目均用于渲染组件。 This component will access the properties of the item like so: 该组件将如下访问项目的属性:

const List = (props) => {
  const listItems = Object.keys(props.list).map((key) => {
    const item = props.list[key];
    return (
      <Item key={item.id} active={item.active}>
        {item.name}
      </Item>
    );
  });

  return <ul>{listItems}</ul>;
};

However, every time I run through the following code, my component (which is a PureComponent) renders. 但是,每次我运行以下代码时,都会渲染我的组件(这是一个PureComponent)。

case UPDATE_LIST_ITEM:
  return {
    ...state,
    list: {
      ...state.list,
      [payload.itemId]: {
        ...state.list[payload.itemId],
      },
    },
  };

The Redux docs mention that "every level of nesting must be copied and updated appropriately", yet, I'm not even updating any values, but just copying the object. Redux文档提到“必须复制并正确更新每个嵌套层”,但是,我什至不更新任何值,而只是复制对象。

I'm not sure what could be done here. 我不确定在这里可以做什么。 Is this a good time to implement a library like Immutable.js? 现在是实现像Immutable.js这样的库的好时机吗?

Update: 更新:

Also (I'm not too sure if this helps but), the following redux update does not cause my component to render: 另外(我不太确定这是否有帮助,但是),以下redux更新不会导致组件渲染:

case UPDATE_LIST_ITEM:
  return {
    ...state,
    list: {
      ...state.list,
      [payload.itemId]: state.list[payload.itemId],
    },
  };

Your pure component is using props.list from the state. 您的纯组件正在使用该州的props.list In your first reducer, by the time your code reaches that point you are updating the application state and if your component is getting list from the application state, the expected behaviour to re-render your component if the props value has changed. 在第一个化简器中,到代码到达该点时,您正在更新应用程序状态,并且如果组件正在从应用程序状态获取list ,则在props值已更改的情况下重新呈现组件的预期行为。

If you do not want your component to re-render on every state change, you can control that with have to upgrade your component to class and control when and when not it should render. 如果您不希望组件在每次状态更改时都重新呈现,则可以通过将组件升级到类并控制何时以及何时不应该呈现来控制组件。 shouldComponentUpdate(nextProps, nextState)

React docs 反应文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM