首页 > 解决方案 > 不可变地更新redux中的对象数组

问题描述

我在这里改变状态,但我不想!我所有不改变状态的尝试都返回了语法错误,所以我转向了这里。

这是我的 redux 数据结构:

controls: (array)[
    0:
        id: "e06c5fbf-6d57-4f5b-a601-bfc4ad265def"
        status: 'complete'
        files: []
    1:
        id: "e06c5fbf-6d57-4f5b-a601-bfc4ad265def"
        status: 'complete'
        files: []
    ...
    ]

// 和我的减速器

export default function frameworkReducer(state = initialState, action) {
    case RECEIVE_CONTROL_STATUS_UPDATE:
            const index = action.payload.index;
            const newState = {...state};
            newState.controls[index] = { ...state.controls[index], status: action.payload.value };
            return newState

标签: reactjsreduximmutabilitymutable

解决方案


这对我有用:

// 减速器

    let index = action.payload.index
    let controls = [...state.controls];
    controls[index] = {...controls[index], status: action.payload.value};
    return {...state, controls}

推荐阅读