Returning value from a function in react

北战南征 提交于 2020-12-26 12:52:38

问题


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

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) [{…}, {…}, {…}]

(the normal value) but then from outside I get

undefined


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/63938206/returning-value-from-a-function-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!