如何判断Redux Action中Axios发送的OTP请求是否成功
解决方案:通过Redux Thunk返回Promise判断请求结果
你不需要额外管理状态,只需要调整Redux Thunk函数和组件提交逻辑,就能直接判断otpRequest是否成功,从而控制弹窗显示。
步骤1:修改Redux Thunk函数,返回Promise
让otpRequest返回axios请求的Promise,这样组件调用await props.otpRequest(...)时,能捕获请求的成功或失败状态:
export const otpRequest = (email,password) => { return (dispatch) => { const url = process.env.REACT_APP_DEV_BACKEND dispatch(getOTPRequest()) // 返回axios请求的Promise,让组件能监听状态 return axios .post(`${url}/api/get_otp`,{ email: email, password: password }) .then(response => { dispatch(getOTPSuccess()) dispatch(showAlert(handleAxiosError(response),"success")); // 可选:返回响应数据供组件后续使用 return response.data; }) .catch(error => { dispatch(showAlert(handleAxiosError(error),"error")); dispatch(getOTPFailure()) // 抛出错误,让组件的catch块能捕获到 throw error; }) } }
步骤2:调整组件提交逻辑,用try/catch判断结果
在handleSubmit中,通过try/catch包裹异步请求,仅在请求成功时打开OTP弹窗:
const handleSubmit = async (event) => { event.preventDefault(); const data = new FormData(event.currentTarget); let email= data.get('email'); let password= data.get('password'); try { // 等待请求完成 await props.otpRequest(email,password); // 仅请求成功时打开弹窗 handleOTPModelOpen(); } catch (error) { // 请求失败时执行这里(action中已处理错误提示,此处可留空或做额外逻辑) console.error('OTP请求失败:', error); } };
原理说明
Redux Thunk允许thunk函数返回任意值,这里我们返回axios请求的Promise,所以组件中await props.otpRequest(...)会等待请求完成:
- 请求成功时,进入
try块的后续代码,执行弹窗打开逻辑 - 请求失败时,thunk中抛出的错误会被
catch块捕获,不会触发弹窗
这样无需额外添加状态管理,直接通过Promise状态判断请求结果,即可实现需求。
内容的提问来源于stack exchange,提问作者Pankaj Singh Rana
相关产品推荐
相关产品推荐

