3

I can't find the way to create a reducer that changes multiple state, the API Rest returns nested data, which I normalize using normalizr library. Here is my code.

Api returns data:

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

Schema normalizr:

import {schema} from 'normalizr';

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

Normalized data: enter image description here

State tree expected: enter image description here

Which should be the reducer that receives the data of the api rest and generates the previous state tree.

4

1 回答 1

7

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

  1. 调度一项updateCountriesAndPeople将由countriesReducer and处理的操作(例如 ex ) peopleReducer
  2. 调度 2 个不同的动作:
    一个 for countriesReducer,我们称之为updateCountries
    一个 for 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的库。它将允许您一次分派多个操作,例如,如果您有一些选择器来构建数据,它们只会被触发一次。

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

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

于 2017-05-12T06:37:47.023 回答