在 Redux reducer 中更新对象中的值
Updating a value in an object in Redux reducer
我希望根据用户输入更新嵌套对象中的值。因此,例如,如果用户选择更新他们的国家和街道,只有这些值将作为 action.payload 传递给缩减程序并更新(其余状态将保持不变)。我提供我的初始状态和减速器:
我的状态:
const initialState = {
userData: [
{
firstName: "",
lastName: "",
country: "",
address: {
street: "",
houseNumber: "",
postalCode: "",
}
}
],
error: null,
};
export default (state = initialState, action) => {
switch (action.type) {
case GET_USER_DATA:
return { ...state, userData: action.payload };
case UPDATE_USER_DATA:
return {
...state,
userData: [{
...state.userData,
...action.payload,
}]
};
default:
return state;
}
};
任何帮助都将非常有用,谢谢!!
您似乎不需要包装对象的数组。如果是这样,请为简单起见将其删除。然后 userData
变成一个普通对象,你的更新变成:
return {
...state,
userData: { // <- no wrapping array, just update the object
...state.userData,
...action.payload,
}
};
由于存在数组,您需要在正确的索引处解构对象。
return {
...state,
userData: [{
...state.userData[0], // <- destructure the object, not the array
...action.payload,
}]
};
如果您确实需要数组,并且会有多个对象,您还需要在操作负载中传递一个标识符,以便知道要更新哪个索引,但根据当前信息,这是最完整的答案。
我希望根据用户输入更新嵌套对象中的值。因此,例如,如果用户选择更新他们的国家和街道,只有这些值将作为 action.payload 传递给缩减程序并更新(其余状态将保持不变)。我提供我的初始状态和减速器:
我的状态:
const initialState = {
userData: [
{
firstName: "",
lastName: "",
country: "",
address: {
street: "",
houseNumber: "",
postalCode: "",
}
}
],
error: null,
};
export default (state = initialState, action) => {
switch (action.type) {
case GET_USER_DATA:
return { ...state, userData: action.payload };
case UPDATE_USER_DATA:
return {
...state,
userData: [{
...state.userData,
...action.payload,
}]
};
default:
return state;
}
};
任何帮助都将非常有用,谢谢!!
您似乎不需要包装对象的数组。如果是这样,请为简单起见将其删除。然后 userData
变成一个普通对象,你的更新变成:
return {
...state,
userData: { // <- no wrapping array, just update the object
...state.userData,
...action.payload,
}
};
由于存在数组,您需要在正确的索引处解构对象。
return {
...state,
userData: [{
...state.userData[0], // <- destructure the object, not the array
...action.payload,
}]
};
如果您确实需要数组,并且会有多个对象,您还需要在操作负载中传递一个标识符,以便知道要更新哪个索引,但根据当前信息,这是最完整的答案。