ngrx Reducer 改变多个状态

ngrx Reducer to change multiple states

我找不到创建可更改多个状态的 reducer 的方法,API Rest returns 嵌套数据,我使用 normalizr 库对其进行了规范化。这是我的代码。

Api returns 数据:

[
  {id: 1, firstName: 'CRISTIAN', lastName: 'QUISPE', country: {id: 1, name: 'PERU'}},
  {id: 2, firstName: 'ISRRAEL', lastName: 'ALCAZAR', country: {id: 10, name: 'ESPAÑA'}}
];

模式标准化:

import {schema} from 'normalizr';

export const country = new schema.Entity('countries');
export const person = new schema.Entity('people', {
  country: country
});

标准化数据:

预期状态树:

哪个应该是reducer接收apirest的数据,生成之前的状态树

获得规范化数据后,您有 2 个解决方案:

  1. 调度一个将由 countriesReducer peopleReducer
  2. 处理的操作(例如 updateCountriesAndPeople
  3. 调度 2 个不同的操作:
    一个代表 countriesReducer,我们称它为 updateCountries
    一个 peopleReducer,我们称它为 updatePeople

第一个非常简单:

const updateCountriesAndPeople = 'UPDATE_COUNTRIES_AND_PEOPLE';

function countriesReducer(state, action) {
  switch(action.type) {
    case updateCountriesAndPeople: {
      // do what you want with payload.entities.countries
    }
  }
}

function peopleReducer(state, action) {
  switch(action.type) {
    case updateCountriesAndPeople: {
      // do what you want with payload.entities.people
    }
  }
}

对于解决方案 n°2,如果您分派 2 个动作,您最终会在 2 个分派之间出现状态不一致。因此,如果你想避免这种情况,你应该使用一个名为 redux-batched-actions 的库。它将允许您一次分派多个操作,例如,如果您有一些选择器来构建数据,它们只会被触发一次。

就个人而言,如果我知道我可能想独立地重复使用那些小动作,有时我喜欢拆分我的动作。

如果您想要非常简单的东西,请采用第 1 号解决方案 :)。