[英]How to update only one value in nested array of Redux state?
Consider the following state: 考虑以下状态:
const initState = {
id: {
data: null,
isFetching: false,
fetchingError: null
},
bookmarks: {
IDs: {
news: [],
opps: [],
posts: []
},
data: {
news: [],
opps: [],
posts: []
},
isFetching: false,
fetchingError: null
},
role: null,
membership: null,
}
How do I update just the posts
array in the ÌDs
array in the bookmarks
array? 如何更新只是
posts
的阵列ÌDs
的数组bookmarks
数组? I tried this: 我尝试了这个:
case 'SET_USER_BOOKMARKED_POSTS':
return {
...state,
bookmarks: {
IDs: {
posts: action.payload
}
}
}
But when I log the state to the console the IDs
array then only contains posts
, while the opps
and news
arrays are not there anymore. 但是,当我将状态记录到控制台时,
IDs
数组仅包含posts
,而opps
和news
数组不再存在。
You need use the spread operator for state.bookmarks.IDs
also as when specifies keys after the spread operator, the value for the keys are overwritten. 您还需要对
state.bookmarks.IDs
使用扩展运算符,因为当在扩展运算符之后指定键时,键的值将被覆盖。
case 'SET_USER_BOOKMARKED_POSTS':
return {
...state,
bookmarks: {
...state.bookmarks
IDs: {
...state.bookmarks.IDs,
posts: action.payload
},
}
}
You need to destruct all inner structure: 您需要破坏所有内部结构:
case 'SET_USER_BOOKMARKED_POSTS':
return {
...state,
bookmarks: {
...state.bookmarks,
IDs: {
...state.bookmarks.IDs,
posts: action.payload
}
}
}
But this is not very convinient, better use lodash merge 但这不是很方便,最好用lodash合并
The way we do it is a non-mutative method using Object.assign
to basically point and update a field in the redux state. 我们这样做的方法是使用
Object.assign
基本上指向并更新redux状态的字段的非变异方法。 Something like: 就像是:
return Object.assign({}, state.bookmarks, {
IDs: action.payload,
});
This will make sure you're not mutating the state, and returns the new bookmarks. 这将确保您不改变状态,并返回新的书签。 You can adjust this to return the entire state if you'd like, it depends on if you need the other data on the update.
您可以根据需要调整此值以返回整个状态,这取决于您是否需要更新中的其他数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.