如何使用redux-thunk和try-catch处理来自React的多个调度结果?

问题描述 投票:0回答:1

我正在使用redux-thunk进行操作调用,而reducer返回状态。我的操作实质上是向后端发送的axios API请求。对于一个特定的动作,我需要按照代码中显示的确切顺序分派一个set事件:

  1. 检查用户传递的tokenvalue是否有效(它对令牌收集有其自己的axios api请求)。如果1.失败,则跳转到catch块。
  2. 如果令牌确实有效,请使用axios帖子注册用户。如果2.失败,则跳到捕获块
  3. 如果用户注册成功,则为用户设置令牌(因此每个用户只有一个唯一的令牌)。如果3.失败,则跳转到catch块。

为了按上述顺序依次实现它们,我将它们放在try-catch块中。原来我对dispatch的工作方式的理解是错误的-如果调度因错误而失败,它仍将执行后续调度。关于如何解决这个问题有什么建议吗? :

export const register = ({name,email,password,tokenval}) => async(dispatch) =>{
try{
    await dispatch(checkTokenValidity(tokenval)); // if this fails, jump to catch block
    const res = await axios.post("/api/users", body, config); //if this fails jump to catch
    await dispatch(setUserToToken({ tokenval, userID: res.data.userID })); //if this fails jump to catch
    dispatch({
      type: REGISTER_SUCCESS,
      payload: res.data,
    });
}catch(err){
  dispatch({
      type: REGISTER_FAIL,
    });
}
};
reactjs promise react-redux redux-thunk
1个回答
0
投票
  • 请确保checkTokenValidity在失败时引发错误。有了它,它会自动转到catch块
  • 无需使用分发并等待令牌有效
  • 存储api会得出变量,并进行必要的检查并相应地调度操作。

您的重构代码

export const register = ({ name, email, password, tokenval }) => async (
  dispatch
) => {
  try {
    const isValidToken = await checkTokenValidity(tokenval); // no need of dispatch - just make sure that the checkTokenValidity throws an error upon fail
    if(!isValidToken ){
        throw new Error('server error - invalid token')
    }
    const usersResult = await axios.post("/api/users", body, config); //if this fails jump to catch
    if(!usersResult ){
        throw new Error('server error - usersResult')
    }
    const setUserToTokenResults = await dispatch(setUserToToken({ tokenval, userID: res.data.userID })); //if this fails jump to catch
    if(!setUserToTokenResults ){
        throw new Error('server error - setUserToTokenResults')
    }
    dispatch({
      type: REGISTER_SUCCESS,
      payload: res.data,
    });
  } catch (err) {
    dispatch({
      type: REGISTER_FAIL,
      payload: {err} //<---- provide some error message to the reducer
    });
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.