从React中的函数返回值 [英] Returning value from a function in react

查看:1879
本文介绍了从React中的函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试从函数中返回res.data,然后进行console.log时,我不确定,但是如果我从函数内部进行console.log时,则得到正常结果

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

所以我先得到

(3)[{...},{...},{...}]

(3) [{…}, {…}, {…}]

(正常值) 但是从外面我得到了

(the normal value) but then from outside I get

未定义

推荐答案

您还需要返回呼叫:

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

这篇关于从React中的函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆