首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Reactjs中实现Axios.get的问题

在Reactjs中实现Axios.get的问题
EN

Stack Overflow用户
提问于 2021-04-29 17:42:49
回答 2查看 46关注 0票数 0

我是个新手,我想根据函数参数发出一个Axios.get()请求。这就是我尝试过的。

代码语言:javascript
复制
 const mentorName = (value) => {
    try {
      Axios.get(
        `${BASE_URL}/api/v1/consultations/${value}`
      ).then(res => {
        if (res.status !== 200 || res.data.status !== "success") {
          console.log(res)
          return
        }
      })
    } catch (error) {
      console.log(error)
    }
  }

但它不起作用,因为在控制台中没有打印res。这里面有什么问题呢?

运行良好的代码是:

代码语言:javascript
复制
const mentorName = (value) => {
    try {
      const res = Axios.get(
        `${BASE_URL}/api/v1/consultations/${value}`
      )
        if (res.status !== 200 || res.data.status !== "success") {
          console.log(res)
          return
      }
    } catch (error) {
      console.log(error)
    }
  }

下面的代码运行良好,但返回了封装在promise中的信息。现在如何访问它,因为res.data不是有效的属性。

EN

回答 2

Stack Overflow用户

发布于 2021-04-29 18:25:15

你能在async/await上试试这个吗?

代码语言:javascript
复制
import axios from 'axios';

const mentorName = async value => {
  try {
    const res = await axios.get(`${BASE_URL}/api/v1/consultations/${value}`);
    console.log(res);
  } catch (error) {
    console.log(error);
  }
};

在console.log inside try块中,您可以检查api response

票数 0
EN

Stack Overflow用户

发布于 2021-04-29 18:36:36

代码语言:javascript
复制
const mentorName = (value) => {
    try {
      Axios.get(
        `${BASE_URL}/api/v1/consultations/${value}`
      ).then(res => {
        if (res.status !== 200 || res.data.status !== "success") {
          console.log(res)
          return
        }
      })
    } catch (error) {
      console.log(error)
    }
  }

由于if条件,上面的代码不会打印,很可能大部分时间状态都是200,而200以外的任何值都会向下钻取到catch块

它在下面的代码中打印promise的原因是,它是一个等待实现的promise,并且您设置的比较/条件非常好,因为res是promise,而res.status是未定义的

代码语言:javascript
复制
const mentorName = (value) => {
    try {
      const res = Axios.get(
        `${BASE_URL}/api/v1/consultations/${value}`
      )
        if (res.status !== 200 || res.data.status !== "success") {
          console.log(res)
          return
      }
    } catch (error) {
      console.log(error)
    }
  }

调整代码以包含else块,您可以始终在控制台中看到打印的内容

代码语言:javascript
复制
const mentorName = (value) => {
        try {
          Axios.get(
            `${BASE_URL}/api/v1/consultations/${value}`
          ).then(res => {
            if (res.status !== 200 || res.data.status !== "success") {
              console.log(res)
              return
            } else {
              console.log(res);
            }
          })
        } catch (error) {
          console.log(error)
        }
      }

我不建议使用async/await,因为有一个紧迫的原因,那就是UI线程会被搁置,直到异步调用得到解决。只是为了让它看起来像一个同步调用。坚持承诺之道。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67314874

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档