我试图找出减速器嵌套数组中项目的宽度更新值和更改值。
这是我的减速器状态:
let initialState = {
data: {
users: [
{
id: 1,
name: 'a'
},
{
id: 2,
name: 'b'
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
我想更改 data.users 中的项目名称,但我无法访问那里
我怎样才能做到这一点?
我试过这个
case SET_NAME:
return {
...state,
users: state.data.users((item, i) =>
item.id == action.payload.id ? { ...item, value: action.payload.value} : null
)
};
Run Code Online (Sandbox Code Playgroud)
但我无法访问用户
尝试这个:
return {
...state,
data: {
// add "state.data" if there is any other data than the users
// array that you don't want to be removed or changed
...state.data,
users: state.data.users((item, i) =>
item.id == action.payload.id
? { ...item, value: action.payload.value }
: null
)
}
Run Code Online (Sandbox Code Playgroud)
如果没有,这应该有效:
// Will loop over the existing users array in the state and return an array.
const updatedUsers = state.data.users.map((item, i) => {
// If the item exist and matches the id of the payload,
// it will update it
if (item.id === action.payload.id) {
item.value = action.payload.value;
}
return item;
});
// And here is a console log to see the updated array
console.log(updatedUsers)
return {
...state,
// This is how you update a nested array
data: { ...state.data, users: updatedUsers }
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1561 次 |
| 最近记录: |