在发出API请求时,我从服务器上获取了一个深层嵌套的对象,从阅读此内容开始,Redux存储嵌套对象数据是一种不好的做法,因此,我在该对象上使用Normalizr,这会给我带来很多不同实体。
我面临的问题是在我的Action中提出该请求时。如何将每个实体有效地存储到不同的化简器中。
action.ts
export const fetchClaim = (claimId: string) => async (dispatch: any) => {
dispatch({ type: REQUEST_CLAIM, payload: true });
try {
const response = await req.get(`claim/${claimId}`);
const normalizedData = normalize(response.data, Claim);
dispatch({ type: SET_LIABILITY, payload: normalizedData.entities.LiabilityType });
dispatch({ type: SET_CLAIM_STATUS, payload: normalizedData.entities.ClaimStatus });
dispatch({ type: SET_CLAIM, payload: normalizedData.entities.Claim });
dispatch({ type: SET_ACTIONS, payload: normalizedData.entities.Actions });
} catch (e) {}
}
然后在我的reducer文件夹中有一个index.ts文件,其中结合了reducers。
import { combineReducers } from 'redux';
import claimReducer from './claimReducer';
import actionReducer from './actionReducer';
import liabilityReducer from './liabilityReducer';
import claimStatusReducer from './claimStatusReducer';
export default combineReducers({
claim: claimReducer,
actions: actionReducer,
liability: liabilityReducer,
claimStatus: claimStatusReducer
});
最后,每个化简器在存储其数据方面看起来都是相同的。
import { LiabilityActionTypes, LiabilityState } from "../types/Liability";
const INITIAL_STATE: LiabilityState = {
liability: null
}
// State - Returns what the state was when this reducer was previously ran.
// Action - This is what the action creator dispatched.
export default (state = INITIAL_STATE, action: LiabilityActionTypes): LiabilityState => {
switch (action.type) {
case 'SET_LIABILITY':
return { ...state, liability: action.payload };
default:
return state;
}
}
我的问题是,如果我有大约40个实体,那似乎不正确,我需要在dispatch
动作中调用fetchClaim
40次。是否有最佳实践来实现这一目标?