【问题标题】:How add an object into the array list that is value of another object in Redux toolkit如何将一个对象添加到数组列表中,该对象是 Redux 工具包中另一个对象的值
【发布时间】:2021-09-05 05:29:27
【问题描述】:

我有一个初始状态,其中包含带有键号的词汇对象,每个键都有对象数组,在 React redux 中,我们使用传播并在 reducer 中更新我们的状态,但在 redux 工具包中,我卡住了,我想添加每个键的数组对象

const initialState: IWordListState = {
  vocabulary: {
    7:[
      {}
    ]
  },
};
export const wordSlice = createSlice({
  name: 'words',
  initialState,
  reducers: {
    addWord: (
      state,
      action: PayloadAction<{ step: number; newWord: WordState }>,
    ) => {
      console.log(current(state));
      const { step, newWord } = action.payload;
      state.vocabulary[step] = [{ ...newWord }];
    },
  },
});

我想在调用 addWord 函数时添加另一个对象,我得到一个步骤号作为词汇对象的键,如下所示:

  vocabulary: {
    7:[
         {
        id:211,
        ....
       },
       {
        id:212,
        ....
       }
    ],
    6:[
      {
        id:213,
        ....

     ]

  },

【问题讨论】:

    标签: javascript reactjs redux redux-toolkit


    【解决方案1】:

    你可以这样更新:

    state.vocabulary[step] = state.vocabulary[step] ? [...state.vocabulary[step], newWord] : [newWord]
    

    【讨论】:

    • 嘿@viet,谢谢,我测试了一下,但我收到了这个错误TypeError: state.vocabulary[step] is not iterable
    • 因为state.vocabulary[step] 不是数组。请再次检查您的数据
    • 我在使用扩展运算符之前用检查条件更新了这个答案
    【解决方案2】:

    检查这个是否有效:

    addWord: (
      state,
      action: PayloadAction<{ step: number; newWord: WordState }>,
    ) => {
      console.log(current(state));
      const { step, newWord } = action.payload;
      state.vocabulary[step].push(newWord);
    },
    

    【讨论】:

    • 谢谢erfan,如果我为每个键设置一个空数组,并且如果我在每次渲染中有很多键,我会存储它们,vocabulary: { 7: [], 6: [], 5: [], },
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2022-08-13
    • 1970-01-01
    • 2021-03-24
    相关资源
    最近更新 更多