Javascript 从react中的函数返回值

Javascript 从react中的函数返回值,javascript,reactjs,function,Javascript,Reactjs,Function,当我试图从函数返回res.data,然后从console.log返回时,我会得到未定义的结果,但如果从函数内部返回console.log,则会得到正常的结果 const getDefaultState=()=>{ axios .get(“http://localhost:5000/urls/todos") 。然后((res)=>{ 如果(资源数据){ console.log(res.data); 返回res.data; } }) .catch((err)=>console.log(err));

当我试图从函数返回res.data,然后从console.log返回时,我会得到未定义的结果,但如果从函数内部返回console.log,则会得到正常的结果

const getDefaultState=()=>{
axios
.get(“http://localhost:5000/urls/todos")
。然后((res)=>{
如果(资源数据){
console.log(res.data);
返回res.data;
}
})
.catch((err)=>console.log(err));
};

log(getDefaultState())您应该返回承诺

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));
这样,您就可以在函数之外收听结果:

getDefaultState().then(/* do stuff */);
// or
const res = await getDefaultState();

您还需要回电话:

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));
}

您可以使用async/awaitAs@sirwanafi建议,您会得到
未定义的
,因为当您console.log(getDefaultState())时,您的请求仍在处理中。请参阅,请注意
getDefaultState
永远不会返回“real”值。你所能做的最好的事情就是让它返回一个承诺。请记住,在有些情况下,你在'then'子句中不返回任何内容,在'catch'子句中也不返回任何内容,因此你仍然可能得到未定义的/null。但是,只要承诺正确解析并且有数据,您就会以这种方式接收它。如果您想使用async,请不要忘记async。您想指出您更改了什么(去掉括号)。