Angular 2 ngrx: 如何更新嵌套在状态数组项中的数组?

3
在我的 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方式进行回放,应该如何处理? 谢谢。
编辑1:REDUCER代码
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代码吗? - chrigu
1个回答

16

假设您的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 上。


很棒的视频,简短而精彩。我推荐未来的观众们去看看! - Richard Dunn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接