我无法更改initialState中的数组(winArray[](。在这里,我从组件级别获取有效载荷。payload有两个值,一个是id,另一个是value。在这里,我使用id作为索引,将值插入winArray。有人能帮我改变状态中的数组吗?
import {createSlice} from '@reduxjs/toolkit';
const initialState={
winArray:['','','','','','','','','']
}
const gameWinSlice=createSlice({
name:'gameWin',
initialState:initialState,
reducers:{
winStatus(state,action){
const id=+action.payload.id
let temp=[...state.winArray];
temp[id]=action.payload.value;
temp.splice(id,0,action.payload.value);
console.log(state.winArray)
return{
...state,
winArray:temp
}
}
}
});
export const gameWinActions =gameWinSlice.actions
export default gameWinSlice;
在createSlice减速器中,您只需执行
state.winArray[+action.payload.id]=action.payload.value;
另请参阅文档中使用immer编写Reducers