【发布时间】:2020-09-17 12:38:22
【问题描述】:
当我尝试从我的函数返回我的 res.data 然后 console.log 它我得到未定义但如果我从函数内部 console.log 它得到正常结果
const getDefaultState = () => {
axios
.get("http://localhost:5000/urls/todos")
.then((res) => {
if (res.data) {
console.log(res.data);
return res.data;
}
})
.catch((err) => console.log(err));
};
console.log(getDefaultState());
所以我先来
(3) [{…}, {…}, {…}]
(正常值) 但后来我从外面得到了
未定义
【问题讨论】:
-
你可以使用 async/await
-
正如@SirwanAfifi 建议的那样,您会得到
undefined,因为当您使用console.log(getDefaultState()) 时,您的请求仍在处理中。见this -
请注意
getDefaultState永远不会返回“真实”值。你能做的最好的就是让它返回一个承诺。
标签: javascript reactjs function