简体   繁体   中英

Redux state update causing React component to render unnecessarily

I'm experiencing a few performance issues in my react / redux app.

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.

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.

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.

I'm not sure what could be done here. Is this a good time to implement a library like Immutable.js?

Update:

Also (I'm not too sure if this helps but), the following redux update does not cause my component to render:

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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