我正在文件中尝试useReducer()
,想知道是否可以使用异步代码,但是在我的console.log()
中,我得到一个空数组,它达到了我的默认值。
关于这是为什么的任何想法?您可以通过函数调用在对象中进行异步/等待吗?
组件文件:
const [state, dispatch] = useReducer(reducer, {})
useEffect(() => {
const getWriteKeys = () => {
dispatch(Actions.getWriteKeys(workspaceUid, sourceUid));
};
getWriteKeys();
}, [dispatch, workspaceUid, sourceUid]);
console.log('state: ', state);
动作文件:
const initialState = {
writeKeys: [],
loading: true,
};
export default {
getWriteKeys: async (workspaceUid, sourceUid) => {
const res = await api.sources.getWriteKeys(workspaceUid, sourceUid);
return {
type: UserActions.SOURCES_GET_WRITE_KEYS,
payload: {
writeKeys: res
}
}
}
};
减速器:
const reducer = (state = initialState, action = {}) => {
switch (action.type) {
case UserActions.SOURCES_GET_WRITE_KEYS:
return { ...state, writeKeys: action.payload.writeKeys, loading: false };
default:
console.log('in default')
return state;
}
};