简体   繁体   English

将索引 object 添加到 Redux 商店(Redux 工具包)的最佳方法是什么?

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

I've been storing everything in arrays up until now, but after coming across this StachOverflow question about keyed object indexes and how traversing arrays can lead to a performance loss, I wanted to shift towards storing stuff as objects.到目前为止,我一直将所有内容存储在 arrays 中,但是在遇到关于键控 object 索引以及遍历 arrays 如何导致性能损失的 StachOverflow 问题之后,我想转向将内容存储为对象。 I don't quite get the syntax however.但是我不太明白语法。

This reducer is meant to create an indexed object but it doesn't seem to work.这个减速器是为了创建一个索引 object 但它似乎不起作用。 How can I fix it to produce the desired object shape below?我怎样才能修复它以产生下面所需的 object 形状?


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] };
    },
  },
});

I want to achieve something like this:我想实现这样的目标:

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

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

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