![](/img/trans.png)
[英]How to update only one object property or multiple in an array using ngrx state in Angular 5?
[英]Angular 2 ngrx : how to update an array which is embedded in one the the items of my state array?
在我的reducer中,我想添加一個像這樣的數組元素:
JSON結構(收到http服務):
{
"id": "09fabf9a-e532-4d2a-87cc-bd949a0a437f",
"title": 'my title',
"itemId": "6d442772-d414-46b1-8aab-a105d2bc3b38",
"createdOn": "2017-01-12T10:12:22.987Z",
**"replays": []**
}
所以我想添加(以及為什么不更新)這個重放數組,它位於reviews數組中。
評論陣列:
[review1,review2,review3...review(n)]
我已經有了一個用於管理評論的reducer,但是如何重播 redux方式呢? 謝謝
編輯1:減少代碼
xport const Reviews: ActionReducer<Array<Review>> = (state: any[] = [], action: Action) => {
switch (action.type) {
case GET_REVIEWS:
return action.payload;
case ADD_REVIEW:
return [...state, action.payload];
case UPDATE_REVIEW:
let index = state.map(review => review.id).indexOf(action.payload.id);
return [
...state.slice(0, index),
Object.assign({}, state[index], action.payload),
...state.slice(index + 1)
];
case DELETE_REVIEW:
return state.filter(item => {
return item.id !== action.payload;
});
case ADD_REPLAY:
return 'HERE I'AM STUCK !'
default:
return state;
}
};
假設您對ADD_REPLAY
操作的操作是具有審閱ID和要添加的重播的對象。 為了不改變對象(重放和復習),你必須替換它們。
case ADD_REPLAY:
let index = state.map(review => review.id).indexOf(action.payload.id);
return [
...state.slice(0, index),
Object.assign({}, state[index], {
replays: [...state[index].replays, action.payload.replay]
}),
...state.slice(index + 1)
];
有一個很棒的免費視頻解釋如何避免egghead上的陣列突變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.