【问题标题】:Returning value from a function in react从反应中的函数返回值
【发布时间】: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


【解决方案1】:

您还需要回电:

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】:

    你应该返回承诺。

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

    【讨论】:

    • 请记住,由于在某些情况下您不会在 'then' 子句中返回任何内容,并且您永远不会在 'catch' 子句中返回任何内容,因此您仍然可能会得到 undefined/null。但只要 promise 正确解析并且有数据,你就会以这种方式收到。
    • 如果你想使用 await,别忘了 async
    • 你介意指出你改变了什么(去掉括号)。
    猜你喜欢
    • 1970-01-01
    • 2021-02-12
    • 2019-02-07
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多