如何将一个对象添加到数组列表中,该列表是 Redux 工具包中另一个对象的值
How add an object into the array list that is value of another object in Redux toolkit
我有一个初始状态,它有一个带有键号的词汇表对象,每个键都有一个对象数组,在 React redux 中,我们使用 spread 并在 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,
....
]
},
您可以这样更新:
state.vocabulary[step] = state.vocabulary[step] ? [...state.vocabulary[step], newWord] : [newWord]
检查这个是否有效:
addWord: (
state,
action: PayloadAction<{ step: number; newWord: WordState }>,
) => {
console.log(current(state));
const { step, newWord } = action.payload;
state.vocabulary[step].push(newWord);
},
我有一个初始状态,它有一个带有键号的词汇表对象,每个键都有一个对象数组,在 React redux 中,我们使用 spread 并在 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,
....
]
},
您可以这样更新:
state.vocabulary[step] = state.vocabulary[step] ? [...state.vocabulary[step], newWord] : [newWord]
检查这个是否有效:
addWord: (
state,
action: PayloadAction<{ step: number; newWord: WordState }>,
) => {
console.log(current(state));
const { step, newWord } = action.payload;
state.vocabulary[step].push(newWord);
},