我试图找出减速器嵌套数组中项目的宽度更新值并更改值。
它是我的减速器状态:
let initialState = {
data: {
users: [
{
id: 1,
name: 'a'
},
{
id: 2,
name: 'b'
}
]
}
}
并且我想更改data.users中项目的名称,但是我不能在那里访问
我该怎么做?
我尝试过
case SET_NAME:
return {
...state,
users: state.data.users((item, i) =>
item.id == action.payload.id ? { ...item, value: action.payload.value} : null
)
};
但我无法访问用户
答案 0 :(得分:1)
尝试一下:
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
)
}
如果没有,这应该可以工作:
// 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 }
};
答案 1 :(得分:1)
举行聚会...
case SET_NAME:
return {
...state,
data: {
...state.data,
users: [
...(state.data.users.map(user =>
user.id === action.payload.id
? { ...user, value: action.payload.value }
: user
))
]
}
};
答案 2 :(得分:1)
减速器似乎有3个问题:
data
users
数组的map函数的调用null
,而不是保留它。您可能会想到这样做:
return {
...state,
data: {
...state.data,
users: state.data.users.map(item =>
item.id == action.payload.id ? { ...item, value: action.payload.value } : item
)
}
};
此操作:
{
type: SET_NAME,
payload: { id: 1, value: 'test' }
}
结果状态为:
{
data: {
users: [
{
id: 1,
name: 'a',
value: 'test'
},
{
id: 2,
name: 'b'
}
]
}
}
如果要从操作中将名称设置为value
,则可以在化简器中覆盖它。在这种情况下,整个减速器将是:
return {
...state,
data: {
...state.data,
users: state.data.users.map(item =>
item.id == action.payload.id ? { ...item, name: action.payload.value } : item
)
}
};
,上述操作的结果状态为:
{
data: {
users: [
{
id: 1,
name: 'test'
},
{
id: 2,
name: 'b'
}
]
}
}