【问题标题】:Angular 2 ngrx : how to update an array which is embedded in one the the items of my state array?Angular 2 ngrx:如何更新嵌入在我的状态数组项中的数组?
【发布时间】:2017-01-12 10:28:40
【问题描述】:

在我的减速器中,我想添加一个像这样的数组中的元素:

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 数组,它位于 reviews 数组中。

评论数组:

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

我已经有一个用于管理评论的 reducer,但是我将如何使用 replays 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;
}

};

【问题讨论】:

  • 你能添加你的reducer代码吗?

标签: javascript arrays angular redux ngrx


【解决方案1】:

假设您对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 上有一个很棒的免费视频解释如何避免数组突变。

【讨论】:

  • 很棒的视频,短小精悍。我建议未来的读者检查一下!
猜你喜欢
  • 1970-01-01
  • 2022-01-11
  • 2019-02-06
  • 1970-01-01
  • 1970-01-01
  • 2018-07-04
  • 2017-04-30
  • 2019-08-28
  • 1970-01-01
相关资源
最近更新 更多