[英]Angular 2 ngrx : how to update an array which is embedded in one the the items of my state array?
In my reducer, i would like to add an element which is in an array like this : 在我的reducer中,我想添加一个像这样的数组元素:
The JSON structure (recieved with http services): 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": []**
}
So I would like to add (and why not update) this replays array, wich is in the reviews array. 所以我想添加(以及为什么不更新)这个重放数组,它位于reviews数组中。
REVIEWS ARRAY : 评论阵列:
[review1,review2,review3...review(n)]
I already have a reducer for managing the reviews, but how would I do it with replays the redux way ? 我已经有了一个用于管理评论的reducer,但是如何重播 redux方式呢? THX 谢谢
EDIT 1 : REDUCER CODE 编辑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;
}
}; };
Assuming your action for the ADD_REPLAY
action is an object with the review's ID plus the Replay to add. 假设您对ADD_REPLAY
操作的操作是具有审阅ID和要添加的重播的对象。 In order to not mutate the objects (replay and review) you have to replace them. 为了不改变对象(重放和复习),你必须替换它们。
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)
];
There's a great free video explaining how to avoid array mutations on egghead . 有一个很棒的免费视频解释如何避免egghead上的阵列突变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.