2017-09-16 19 views
0

行動有效載荷陣列我有,從我的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 
    } 
] 

然後,我所說的「願望清單」另一個存儲陣列,它看起來像這樣:

[ 
    { 
     "id": 4311, 
     "title": "C43- Miami Bow Cabinet Handles High Quality Stainless Steel (Polished) Handles", 
     "liked": true 
    } 
] 

我想要做的是測試如果每個崗位是心願數組中,並更新了「喜歡」該帖子的關鍵。在這種情況下,id爲4311的帖子在wishlist數組中,所以應該將其''喜歡''鍵更新爲true。我不能這樣做arr.includes(),因爲posts數組中的帖子與wishlist數組中的帖子不匹配(因爲'喜歡'的鍵不一樣)。

所以這是我的想法是:

  1. 通過規範化的心願ID的
  2. 然後柱陣圖和檢查ID的比賽
  3. 更新該職位
的喜歡關鍵

我已經得到了步驟1 & 2下載,這裏是我的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

試試我的方法

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

您能夠在這段代碼擴展,我不是100%肯定這是如何聯繫起來什麼我已經 – rhysclay

+0

對不起,我被誤解了。答案已編輯。我的方式是通過使用「地圖」返回新帖子,並通過「查找(p => p.id === item.id)」來檢查在actions.posts中的帖子狀態。 –

+0

謝謝你的幫助,我用你的方法論,但略有不同,並解決它! – rhysclay