angular - ngrx Reducer 改变多个状态

标签 angular ngrx ngrx-store

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

API 返回数据:

[
  {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
});

标准化数据: enter image description here

预期状态树: enter image description here

应该是reducer接收api rest的数据,生成之前的state tree。

最佳答案

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

  1. 调度一个将由 countriesReducer peopleReducer 处理的操作(例如 updateCountriesAndPeople)
  2. 调度 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,如果您分派(dispatch) 2 个 Action ,您最终会在 2 个分派(dispatch)之间出现状态不一致。因此,如果你想避免这种情况,你应该使用一个名为 redux-batched-actions 的库。 .它将允许您一次分派(dispatch)多个操作,例如,如果您有一些选择器来构建数据,它们只会被触发一次。

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

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

关于angular - ngrx Reducer 改变多个状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43927997/

相关文章:

Angular 2 验证器未按预期工作

javascript - Angular 4.3 拦截器不工作

angular - ngrx 8 : Access state of @ngrx/data entity from reducer function

angular - 在 Angular 中导入 @ngrx/core @ngrx/store 时出现问题

angular - TypeError : undefined is not iterable (cannot read property Symbol(Symbol. iterator)) 用于效果、选择器、服务 [Angular 11]

angular charts.js 圆环图动态设置中心文本

angular - NativeScript Angular 6 双向绑定(bind)在 TextField 上不起作用

javascript - 在for循环中以 Angular 2链接http调用

javascript - 使用 Angular 6 延迟加载时,ngrx 的最佳文件夹结构是什么?

javascript - @ngrx - 将商店查询链接到BehaviorSubject