如何在useReducer()操作文件中使用Async / Await

时间:2020-09-23 00:17:16

标签: reactjs async-await use-reducer

我正在文件中尝试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;
  }
};

0 个答案:

没有答案