reactjs - 如何使用 redux-thunk 和 try-catch 处理多个调度结果?
问题描述
我正在使用 redux-thunk 进行操作调用和减速器返回状态。我的操作本质上是对后端的 axios API 请求。对于一个特定的操作,我需要按照代码中显示的确切顺序调度一组事件:
- 检查
tokenvalue
用户传递的是否有效(对 tokencollection 有自己的 axios api 请求)。如果 1. 失败,跳转到 catch 块。 - 如果令牌确实有效,请使用 axios post 注册用户。如果 2. 失败,跳转到 catch 块
- 如果用户注册成功,将令牌设置给用户(因此每个用户只有一个唯一令牌)。如果 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,
});
}
};
解决方案
- 确保 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
});
}
};
推荐阅读
- sql - Retrieving data from a reader and saving it in a double variable
- sqlite - 不要在 SQLLite 查询中因缺少列而失败
- android - Can someone please assist me with this Ionic Project
- spring-boot - 我是否需要用于 spring-boot 中的测试的配置文件?
- email - 调用 gmail api 以发送带有附件(多部分)的电子邮件时,请求的正文如何?
- r - 使用 dplyr 哪个字段不同?
- python - 无法在 Azure Databricks 中通过 PyPi 安装 python 包
- ios - 将带有其他参数的图像的 base64String 发布到服务器目标 c
- reactjs - 如果我想允许其他数字输入字段为空,我是否必须将输入值保存为字符串?
- shadow-dom - Shadow DOM 如何影响 stenciljs 中的组件生命周期方法