不可变地更新 redux 中的对象数组
immutably update array of objects in 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
这对我有用:
// 减速机
let index = action.payload.index
let controls = [...state.controls];
controls[index] = {...controls[index], status: action.payload.value};
return {...state, controls}
如果您正在查找和更新特定的 row/item。
case RECEIVE_CONTROL_STATUS_UPDATE:
let findItem = state.controls.find(a=>a.index===action.payload.index);
let filtered = state.controls.filter(a=>a.index!==action.payload.index);
let updateState = [filtered, findItem];
return {
...state,
constrols: updatedState
}
我在这里改变状态,但我不想!我所有不改变状态的尝试都返回语法错误,所以我转向这里。
这是我的 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
这对我有用:
// 减速机
let index = action.payload.index
let controls = [...state.controls];
controls[index] = {...controls[index], status: action.payload.value};
return {...state, controls}
如果您正在查找和更新特定的 row/item。
case RECEIVE_CONTROL_STATUS_UPDATE:
let findItem = state.controls.find(a=>a.index===action.payload.index);
let filtered = state.controls.filter(a=>a.index!==action.payload.index);
let updateState = [filtered, findItem];
return {
...state,
constrols: updatedState
}