reactjs - 在 useEffect 挂钩中访问 Promise 的值
问题描述
const useOnfidoFetch = (URL) => {
useEffect(() => {
const appToken = axios.get('http://localhost:5000/post_stuff')
.then((response) => response.data.data.data.json_data)
.then((json_data) => {
const id = json_data.applicant_id;
const token = json_data.onfido_sdk_token;
return {id, token};
});
if (appToken) {
console.log('this is working!');
OnfidoSDK.init({
// the JWT token you generated above
token: null,
containerId: "root",
steps: [
{
type: 'welcome',
options: {
title: 'Open your new bank account',
},
},
'document'
],
onComplete: function (data) {
console.log('everything is complete');
axios.post('https://third/party/api/v2/server-api/anonymous_invoke?aid=onfido_webapp', {
params: {
applicant_id: appToken.applicant_id
}
});
}
});
}
}, [URL]);
}
export default function() {
const URL = `${transmitAPI}/anonymous_invoke?aid=onfido_webapp`;
const result = useOnfidoFetch(URL, {});
return (
<div id={onfidoContainerId} />
);
}
我已经对其进行了数十次重构,我从appToken
Promise 中取回了一些值,但是我需要token
将该 Promise 中的值提供给token
内部的该属性,Onfido.init({})
并且我需要提供id
该applicant_id
属性并继续获取undefined
.
解决方案
将整个if(appToken){ ... }
内部移动到第二个 .then((json_data) => { ... })
像这样的东西:
const useOnfidoFetch = (URL) => {
useEffect(() => {
const appToken = axios.get('http://localhost:5000/post_stuff')
.then((response) => response.data.data.data.json_data)
.then((json_data) => {
const id = json_data.applicant_id;
const token = json_data.onfido_sdk_token;
// Here. This code will be executed after the values are available for id and token
if (appToken) {
console.log('this is working!');
OnfidoSDK.init({
// the JWT token you generated above
token: null,
containerId: "root",
steps: [
{
type: 'welcome',
options: {
title: 'Open your new bank account',
},
},
'document'
],
onComplete: function (data) {
console.log('everything is complete');
axios.post('https://third/party/api/v2/server-api/anonymous_invoke?aid=onfido_webapp', {
params: {
applicant_id: appToken.applicant_id
}
});
}
});
}
return {id, token};
});
// In here the promise is not yet finished executing, so `id` and `token` are not yet available
}, [URL]);
};
export default function() {
const URL = `${transmitAPI}/anonymous_invoke?aid=onfido_webapp`;
const result = useOnfidoFetch(URL, {});
return (
<div id={onfidoContainerId} />
);
}
为了更好的可读性,您还可以将if(appToken){ ... }
块移动到一个单独的函数中,该函数将id, token
作为参数,您可以从promise.then
块内部调用该函数。
推荐阅读
- python - Matplotlib 切断放置在轴外的图例,忽略 savefig 中的 bbox_extra_artists 参数
- javascript - Lodash keyBy 与数组相同的属性
- python - 无法让我的程序生成随机卡片(1-13)
- c# - 在 DataTemplate UWP 中将点击器绑定到 VM
- php - PHP继承构造函数不起作用
- record - graphviz/dot 中记录内的边
- javascript - jQuery .height() 没有改变
- javascript - 输入格式 jQuery
- dojo - Dojo 列表文本框 - 许多值导致水平滚动 - 如何留在表格单元格中?
- c# - 在 XAML (UWP) 中绑定单例