【发布时间】:2020-10-23 00:45:37
【问题描述】:
我的文件中有这种格式的 useEffect
useEffect(() => {
async function func1(){
//fetching data from database storing it in variable
const options = {
headers: {
Accept: "application/json",
"Content-type": "application/json",
},
};
fetch(process.env.REACT_APP_DB_URI + "/icty/" + setzip, options)
.then((res) => res.json())
.then(
(result) => {
..... setAddressCurrent(result)
}
async function func2 (){
if (user.address) {
const data = user.address;
let zip;
var bar = new Promise((resolve, reject) => {
Object.keys(data).forEach(function (key, index, array) {
if (data[key].types) {
data[key].types.forEach((x) => {
if (x === "route") {
Cookies.set("street", data[key]["long_name"]);
}
if (x === "street_number") {
Cookies.set("street_number", data[key]["long_name"]);
}
});
}
});
});
if(addressCurrent === user.address) return 1;
return bar.then(() => {
return zip;
});
}
}
func1()
func2() //------> how to call this one after func1 is finished doing all job
}, []);
由于问题 func2 在 func1 完成之前被调用,我有未定义的变量。 有人知道如何在 React Hooks 中轻松解决这个问题吗? 修改后的代码
【问题讨论】:
-
由于这些返回承诺,您需要使用
func1().then(() => func2())
标签: reactjs react-hooks use-effect