【问题标题】:Add item to nested array in redux-toolkit将项目添加到 redux-toolkit 中的嵌套数组
【发布时间】:2020-07-01 20:37:19
【问题描述】:

Redux Toolkit 在尝试更新嵌套数组的状态时出现突变错误,我认为它使用 immer 来解决这个问题并简化 reducer。

我的商店看起来像:

状态 -> 表格 -> 部分

我想在现有表单中添加一个部分。

我的操作需要一个表格和一个部分

reducer 看起来像

let intialState={
    forms:[]
}

const FormsReducer = createReducer(intialState, {
    ADD_SECTION: (state, action) => {
        const index = state.forms.findIndex(f => f.id === action.form.id);
        state.forms[index].__formSections.push(action.payload);
        },

在调度中检测到状态突变,在路径中:FormsReducer.forms.0.__formSections.0

然而,根据 redux-toolkit 文档,应该可以“编写”可变的“不可变更新逻辑”...

我做错了什么,我该如何解决?

【问题讨论】:

标签: redux-toolkit


【解决方案1】:

如果你在没有从 reducer 中改变的情况下返回它,则不会发生错误


const FormsReducer = createReducer(intialState, {
    ADD_SECTION: (state, action) => {
        const newstate = {...state}
        const index = newstate.forms.findIndex(f => f.id === action.form.id);
        newstate.forms[index].__formSections.push(action.payload);
        return newstate 
},

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    相关资源
    最近更新 更多