我正在使用redux-thunk进行操作调用,而reducer返回状态。我的操作实质上是向后端发送的axios API请求。对于一个特定的动作,我需要按照代码中显示的确切顺序分派一个set事件:
tokenvalue
是否有效(它对令牌收集有其自己的axios api请求)。如果1.失败,则跳转到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,
});
}
};
您的重构代码
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
});
}
};