ngrx Reducer更改多个状态

cri*_*nqr 3 ngrx angular 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'}}
];
Run Code Online (Sandbox Code Playgroud)

架构规范:

import {schema} from 'normalizr';

export const country = new schema.Entity('countries');
export const person = new schema.Entity('people', {
  country: country
});
Run Code Online (Sandbox Code Playgroud)

归一化数据: 在此处输入图片说明

预期的状态树: 在此处输入图片说明

哪个应该是接收api rest数据并生成先前状态树的reducer。

max*_*992 5

获得规范化数据后,您将有两种解决方案:

  1. 派遣一个updateCountriesAndPeople将由处理的动作(例如ex )countriesReducer peopleReducer
  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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

如果您想要简单的东西,请采取n°1 :)的解决方案。