Angular Ngrx 存储状态中有多个数组

Angular Ngrx store with multiple Arrays in state

我是第一次尝试使用 Ngrx,我一直在关注这个教程https://www.techiediaries.com/angular-10-ngrx-store-example/

我的问题是我可以用这样的东西来定义我的状态:

export interface AppState {
    readonly firstArray: Number[];
    readonly secondArray: Number[];
    readonly thirdArray: Number[];
}

在这种情况下,我应该如何实施我的减速器:

export const UPDATE_DATA = 'TEMP';

export function tempReducer(state: /* How to initialize three empty arrays here ? */, action) {
  switch (action.type) {
    case TEMP:
        /*How to Update arrays here? */
    default:
        return state;
    }
}

还有可能更新状态中的整个数组吗? (例如,将一个新数组分配给 firstArray,而不仅仅是从中添加或删除元素)

根据您提供的内容(包括教程源),您有几个选择。您可以为每个数组使用 1 个 reducer,因为每个数组都成为状态的一部分(也称为切片),或者您可以拥有一个包含 3 个数组的对象,然后为该对象使用 1 个 reducer。对于第二个选项,您将必须管理 reducer 中对象的 3 个数组(所有属性)的状态。

以下是一些示例,但我做了一些假设,因此您可能需要进行一些调整。

选项 1: 在你的根模块中

imports: [
    ...
    StoreModule.forRoot({
        firstArray: firstArrayReducer,
        secondArray: secondArrayReducer,
        thirdArray: thirdArrayReducer
    });
]

您的减速器代码可能如下所示:

export const ADD_DATA    = 'ADD';
export const UPDATE_DATA = 'UPDATE';

export function firstArrayReducer(state: YourFirstArrayType[] = [], action) {
  switch (action.type) {
    case ADD_DATA:
        // This will create a shallow copy of the array and
        // append your latest element to it
        return [...state, action.payload];
    case UPDATE_DATA:
        // Clone your array and return it with the desired modification
        const shallowClone = [...state];
        shallowClone[1] = action.payload; // This is an example
        return shallowClone;
    default:
        return state;
    }
}

选项 2: 是相似的,但不是你的状态是一个简单的数组,它可以是一个对象,而这个对象又会有 3 个数组。

在你的根模块中

imports: [
    ...
    StoreModule.forRoot({ objOfArrays: objArraysReducer });
]

您的减速器代码可能如下所示:

export const ADD_DATA    = 'ADD';
export const UPDATE_DATA = 'UPDATE';

export const initialState = {
    firstArray: [],
    secondArray: [],
    thirdArray: []
};

export function objArraysReducer (state: YourObjectType = initialState, action) 
{
  // Now you need to find a way to detect what has change and update accordingly
  switch (action.type) {
    case ADD_DATA:
        // Your code...
        return state;
    default:
        return state;
    }
}

Also is it possible to update the whole array inside the state ? (for example assign a new array to firstArray and not only add or remove elements from it)

这不仅是可能的,因为它是理想的行为,也是 NgRx 构建的完整原则。上面我使用了新数组而不是改变它们。