[英]Returning value from a function in react
When I'm trying to return my res.data from my function and then console.log it I get undefined but if I console.log it from inside the function I get the normal result当我试图从我的函数返回我的 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());
so I get first所以我先
(3) [{…}, {…}, {…}]
(3) [{…}, {…}, {…}]
(the normal value) but then from outside I get (正常值)但是从外面我得到
undefined
不明确的
You need to return the call as well:您还需要回电:
const getDefaultState = () => {
return axios.get("http://localhost:5000/urls/todos")
.then((res) => {
if (res.data) {
console.log(res.data);
return res.data;
}
}).catch((err) => console.log(err));
}
You should return the promise instead.你应该返回承诺。
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));
That way you can listen to the result outside the function:这样你就可以在函数之外收听结果:
getDefaultState().then(/* do stuff */);
// or
const res = await getDefaultState();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.