【问题标题】:User aync-await in the react-redux thunk在 react-redux thunk 中使用 async-await
【发布时间】:2019-09-09 14:52:45
【问题描述】:

我是 react-redux 的新手。在这里,我尝试使用 aysnc-await 。我在 componentDidMount 上调用了一个 api,如果在那里我得到了200 Ok,那么我只想调用第二个 api。所以我为此使用async-await

export function fetchUserResumes(pageNo, jdId) {
  pageNo = 0;
  let size = 20;
  return (dispatch) => {
    const page = `page=${pageNo}`;
    let url = FETCH_RESUMES + '/' + jdId + '?' + page + '&' + size;
    dispatch({
      type: REQUEST_INITIATED
    })
    return get(url)
      .then((response) => {
        if (response.status === 200) {
          dispatch({
            type: FETCHING_RESUME_SUCCESS,
            data: response.payload
          })
          dispatch({
            type: REQUEST_SUCCESSED
          })
        } else {
          if (!response.status) {
            toastr.error('Our server is down. Please check again');
          }
          else if (response.status.status === 401) {
            dispatch(logout());
          }
          else if (response.status.status === 500) {
            toastr.error("Error while fetching Job description,Please try again");
            dispatch({
              type: FETCHING_RESUME_FAILED,
              data: response.status,
            });
            dispatch({
              type: REQUEST_SUCCESSED
            })
          } else {
            dispatch({
              type: REQUEST_SUCCESSED
            })
          }
        }
        return true;
      })
  }
};

在 didmout 上被调用的动作是

export function getUserJobInfo(jobId) {
  return async (dispatch) => {
    dispatch({
      type: REQUEST_INITIATED
    });
    let url = GET_JOB_INFO_URL + jobId;
    let response = await get(url);
    if (response.status === 200) {
      let pageNo = 0;
      let size = 20;
      const page = `page=${pageNo}`;
      let url = FETCH_RESUMES + '/' + jobId + '?' + page + '&' + size;
      let newApiResponse = await get(dispatch(fetchUserResumes(pageNo, jobId)));
      dispatch({
        type: USER_JOB_INFO,
        data: response.payload
      })
    }
    else {
    }
  }
}

这就是我试图做到这一点的方式。但是在这里我在使用异步等待时变得非常困惑。所以任何人都可以帮助我解决这个问题。 谢谢。

【问题讨论】:

  • get(dispatch(fetchUserResumes 这个get 似乎无效。它对 args 的期望是什么,调度返回是什么?我认为您在这里不需要get。只需将其删除。 Dispatch 将通过 fetch 方法的 promise 返回
  • 是的,这是错误的
  • 那么,这个methid应该是什么结构呢?
  • 等待 (dispatch(fetchUserResumes(pageNo, jobId)));在方法中使用了这个。

标签: reactjs redux async-await react-redux redux-thunk


【解决方案1】:

您无需在await get(dispatch(fetchUserResumes(pageNo, jobId))); 上致电get

在 thunk 的情况下,dispatch 返回与返回内部函数相同的内容。因此,在您的情况下,此调度的返回类型将是 Promiseawait 适用于任何承诺。

  let newApiResponse = await dispatch(fetchUserResumes(pageNo, jobId));

【讨论】:

    猜你喜欢
    • 2021-09-11
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    • 2016-04-28
    • 1970-01-01
    • 2019-02-02
    • 2019-04-24
    相关资源
    最近更新 更多