我有从我的API返回的一系列帖子,看起来像这样:
[
{
"id": 4311,
"title": "C43- Miami Bow Cabinet Handles High Quality Stainless Steel (Polished) Handles",
"liked": false
},
{
"id": 2235,
"title": "C43- Miami Bow Cabinet Handles High Quality Stainless Steel (Brushed) Handles",
"liked": false
}
]
然后,我有另一个名为“ wishlist”的存储数组,如下所示:
[
{
"id": 4311,
"title": "C43- Miami Bow Cabinet Handles High Quality Stainless Steel (Polished) Handles",
"liked": true
}
]
我想做的是测试每个帖子是否在心愿单数组中,并更新该帖子的“喜欢”键。在这种情况下,ID为4311的帖子位于心愿单数组中,因此应将其“喜欢”的键更新为true。我无法执行arr.includes(),因为posts数组中的帖子与wishlist数组中的帖子不匹配(因为“ liked”键相同)。
所以这就是我的想法:
通过ID标准化愿望清单
然后映射posts数组并检查id是否匹配
更新该帖子的喜欢的键
我有第1步和第2步downpat,这是我的JavaScript:
// lets normalize our list of ids
let wishlistByID = state.wishlist.map(function(post) {
return post['id']
})
// now lets map our posts array and see if the id's match
let inWishlist = action.posts.map(function(post) {
return wishlistByID.includes(post['id'])
// returns true when they match
})
但是我不确定如何执行步骤3。这里是我的减速器供参考:
return {
...state,
posts: action.posts,
isFetching: false,
}
任何帮助表示赞赏-这也解决了我遇到的另一个未解决的问题
**更新-感谢@Giang Lee的帮助,我创建了一个新的帖子常量,该常量可以映射到帖子中,如果该帖子的ID与wishlistByID数组匹配,则只需更新喜欢的键即可。
// lets normalize our list of ids
let wishlistByID = state.wishlist.map(function(post) {
return post['id']
})
// now lets map our posts array and see if the id's match
// den just up the liked key to true
const posts = action.posts.map(function(post) {
if(wishlistByID.includes(post['id'])) {
post['liked'] = true
}
return post
})
return {
...state,
posts: posts,
isFetching: false,
最佳答案
尝试我的方式
const posts = state.posts.map((item) => {
const post = action.posts.find(p => p.id === item.id);
return post ? post : item;
});
return {
...state,
posts,
isFetching: false,
}
关于javascript - 需要帮助更新Redux Reducer中的 Action 有效载荷数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46249180/