将索引对象添加到 Redux 存储 (Redux Toolkit) 的最佳方法是什么?

What's the best way to add an indexed object to a Redux store (Redux Toolkit)?

到目前为止,我一直将所有内容存储在数组中,但是在遇到 以及遍历数组如何导致性能损失之后,我想转向将内容存储为对象。但是我不太明白语法。

这个 reducer 是用来创建索引对象的,但它似乎不起作用。 如何修复它以生成下面所需的对象形状?


type MsgPayload = {
  type: string;
  msgKey?: string;
  index?: number;
};

type IndexedMsgPayload = {
  [key: number]: MsgPayload;
};

const messengerSlice = createSlice({
  name: "messages",
  initialState,
  reducers: {
    emitMessage: (state, action: PayloadAction<MsgPayload | any>) => {
      state.total++;
      const indexedObj: IndexedMsgPayload = {
        0: {
          ...action.payload,
        },
      };
      action.payload[state.total] = indexedObj[0];
      state.messages = { ...state.messages, ...action.payload[state.total] };
    },
  },
});

我想实现这样的目标:

{
   1: { 
    type: 'type',
    msgKey: 'alert'
  },
}

Redux Toolkit 已经有一个 createEntityAdapter API 可以为您完成定义和更新规范化状态结构的工作: