更新深度嵌套对象中的单个状态值



希望在深度嵌套状态下更新单个值。由于复杂性,不确定如何更新深度嵌套状态。我已经能够命中数组中的对象,但不知道如何更新该值的状态。

我知道redux工具包使用immer,所以我不认为我必须分散我的状态,但不是100%确定。

const initialState = {
first: {
1: {},
2: [
aa: {
a: '',
z: '',
d: ['dance', 'door', 'drill'],
},
bb: {
...
}  
]
},
second: [],
third: {}
}
const mySlice = createSlice({
name: 'mySlice',
initialState,
reducers:
getObjA(state, action) {
const objA = state.first.1.2.aa.find(obj => obj.a); //Can get to object here.
objA = action.payload; //does not update the object
}
});
export const {getObjA} = mySlice.actions;
export default mySlice.reducer;

你是对的,redux工具包可以让你改变状态对象。此外,您不能在声明后更改const

我建议你使用findIndexsplice:

const objAIndex = state.first.1.2.findIndex(obj => obj.a);
state.first.1.2.splice(objAIndex,1,action.payload)

最新更新