那些来这里寻找钩子combineReducers()
函数的人useReducer()
,这可能对你有帮助
const combineReducers = (...reducers: Function[]) =>
(state: any = initialState, action: any): any => {
for(let i=0;i<reducers.length;i++)
state = reducers[i](state, action)
return state;
}
将此用作
// At module level, so the combined function doesn't change.
const combinedReducer = combineReducers(reducer1, reducer2);
// Inside your component.
const [state, dispatch] = useReducer(combinedReducer, initialState)
编辑:我最近喜欢减少功能,我认为它的实现方式更干净
const combineReducers = (...reducers) =>
(state, action) =>
reducers.reduce((newState, reducer) =>
reducer(newState, action), state)