gpt4 book ai didi

javascript - Angular 2 ngrx : how to update an array which is embedded in one the the items of my state array?

转载 作者:太空狗 更新时间:2023-10-29 18:03:42 25 4
gpt4 key购买 nike

在我的 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": []**
}

所以我想添加(为什么不更新)这个 replays 数组,它在评论数组中。

评论数组:

[review1,review2,review3...review(n)]

我已经有一个用于管理评论的 reducer,但是我如何使用 redux 方式使用 replays 来做到这一点?谢谢

编辑 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 以及要添加的 Replay 的对象。为了不改变对象(重播和审查),您必须替换它们。

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 上的数组突变.

关于javascript - Angular 2 ngrx : how to update an array which is embedded in one the the items of my state array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41610756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com