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。
获得规范化数据后,您将有两种解决方案:
updateCountriesAndPeople将由和处理的动作(例如ex )countriesReducer peopleReducercountriesReducer,我们称它为updateCountriespeopleReducer,我们称它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 :)的解决方案。