本文介绍了Angular 6 ngrx,如何在状态对象的数组中添加新项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的情况,我有诸如CreatUser,CreateSuccess,CreateFail之类的操作.当调度Create动作或CreateSuccess时,应如何将新对象添加到数组?那我该怎么办呢?

I have a simple situation, I have actions Like CreatUser, CreateSuccess, CreateFail. How should I add new object to array and when Create action is dispatched or CreateSuccess? And how should I do that?

export function reducer(state = init, action: Actions): State {
switch (action.type) {
    case ActionsTypes.CREATE:
        return {
            ...state,
            inProgress: true
        };
    case ActionsTypes.CREATE_SUCCESS:
        return {
            ...state,
            users: state.users.push(action.payload),
            inProgress: false
        };
    case ActionsTypes.CREATE_FAIL:
        return {
            ...state,
            error: action.payload,
            inProgress: false
        };
    default:
        return state;
}

在上面的代码中,我尝试使用push方法添加新用户,但这不是一个好的解决方案.我该怎么办?

In code above I tried to add new user using push method, but it is not good solution. How should I do that?

推荐答案

尝试使用传播运算符,因为它创建了一个新的用户数组,并且不会更改前一个数组.

Try to use the spread operator because it creates a new array of users and does not mutate the previous array.

users: [...state.users, action.payload]

否则使用 @ ngrx/entity 模块用于数组.这是最好的方法.

Or else use @ngrx/entity module for arrays. It's the best way.

更新13.07.2019

新模块 @ ngrx/data 在NgRx 8中可用.该模块有助于为以下内容创建CRUD存储:具有零样板的数组.

New module @ngrx/data is available in NgRx 8. This module helps to create CRUD store for arrays with zero boilerplate.

这篇关于Angular 6 ngrx,如何在状态对象的数组中添加新项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 13:36