问题:useReducer
生成的dispatch
无法dispatch
函数
解决:使用useThunkReducer
代替useReducer
const wrapperDispatch = (dispatch, getState) => {
return (action) => {
if (typeof action === 'function') {
action(wrapperDispatch(dispatch, getState), getState);
} else {
dispatch(action);
}
};
};
export const useThunkReducer = (reducer, defaultState) => {
const [state, dispatch] = useReducer(reducer, defaultState);
const getState = () => state;
const newDispatch = wrapperDispatch(dispatch, getState);
return [state, newDispatch];
};