需要帮助在redux reducer

时间:2017-09-16 01:15:36

标签: javascript arrays reactjs redux

我有一系列从我的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的帖子位于wishlist数组中,因此应将其“fav”键更新为true。我不能做arr.includes()因为posts数组中的帖子与wishlist数组中的帖子不匹配(因为'like'键不相同)。

所以这就是我的想法:

  1. 按ID
  2. 标准化心愿单
  3. 然后映射posts数组并检查id是否匹配
  4. 更新该帖子的fav键
  5. 我有步骤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,
    

1 个答案:

答案 0 :(得分:1)

试试我的方式

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,
  }