【问题标题】:I am unable to mutate the array in the Redux state我无法在 Redux 状态下改变数组
【发布时间】:2021-07-31 01:26:21
【问题描述】:

我无法在 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;

【问题讨论】:

    标签: reactjs redux react-redux redux-thunk


    【解决方案1】:

    在 createSlice reducers 中,你可以这样做

      state.winArray[+action.payload.id]=action.payload.value;
    

    另请参阅文档中的 Writing Reducers with immer

    【讨论】:

    • 嗨,@phry 非常感谢!响应,但它不起作用☹️。
    • 你确定是这部分不工作吗?你是否在 Redux Devtools 中验证了 action 已经被调度并且 store 没有工作?
    猜你喜欢
    • 2019-04-29
    • 2019-02-03
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多