reactjs - 在 React/Redux 中获取 Dispatch 的价值
问题描述
我正在尝试通过 twilio api 实现帐户验证,它向用户发送代码,它应该将状态设置generatedCode
为该值,但我很难获得调度的该值。如果我await
用 axios 做一个简单的调用,它可以正常工作,但对于调度来说就不那么好了
行动:
export const attemptRegisterVerify = (phone) => async (dispatch) => {
dispatch(registerVerifyBegin());
await postRegisterVerifyPhone(phone)
.then((res) => {
dispatch(registerVerifySuccess(res.data));
})
.catch((error) => {
dispatch(registerVerifyFail(error));
});
};
处理验证:
const handleVerification = async (values) => {
const { email, phone } = values;
setModal(true);
try {
const response = await axios.post(
'http://localhost:8000/api/v1/auth/register/check-duplicate',
{
email,
phone,
}
);
if (response.data.success) {
switch (response.data.message) {
case 0:
try {
const response = await dispatch(
attemptRegisterVerify({ to: phone })
);
console.log(response);
// if (response.data.success) {
// setGeneratedCode(response.data.message);
// console.log(generatedCode);
// } else {
// console.log(response.data.message);
// }
} catch (error) {
console.log(error);
}
break;
case 1:
console.log('Email Address already in use.');
break;
case 2:
console.log('Phone number already in use.');
break;
case 3:
console.log('Email and Phone in use.');
break;
}
} else {
console.log(response.data.message);
}
} catch (error) {
console.log(error);
}
};
console.log(response) 返回undefined
。有没有办法让它等到调度完成,然后继续?
export const attemptRegisterVerify = (phone) => async (dispatch) => {
dispatch(registerVerifyBegin());
await postRegisterVerifyPhone(phone)
.then((res) => {
dispatch(registerVerifySuccess(res.data));
return res.data; // return console.log(res.data) works
})
.catch((error) => {
dispatch(registerVerifyFail(error));
});
};
解决方案
Dispatch 返回您在函数调用中返回的内容。在异步 thunk 的情况Promise<void>
下,除非您返回某些内容,否则它将默认返回。
如果在您的attemptRegisterVerify
thunk 中,如果您添加return 'test'
到它的末尾,那么您console.log(response)
将记录'test'
.
在非 thunk 中,调度的返回值将是生成的操作。
推荐阅读
- python - QT Designer for Python中的Unicode字符?
- c# - Service Fabric Mesh 中的 Actor 不工作 - 无法加载 DLL FabricRuntime.dll
- javascript - 为什么我会收到“TypeError:'__source' 的属性未定义:对象不可扩展。” IE11 出错?
- reactjs - 如何从装饰组件访问 EditorState
- php - WooCommerce 在添加到购物车后以模式获取产品 ID(在产品页面上使用 ajax)
- ios - ARKit 从 url 添加参考图像
- javascript - 在 Gatsby CMS 上,我如何将关于页面设置为索引页面
- reporting-services - 如何选择数据集中的最新年份?
- google-cloud-platform - 更改 Google Cloud 中单个虚拟机的所有权
- console - 如何在开发控制台中发现卡顿?