【问题标题】:Async useEffect does not work for fetching data [duplicate]异步 useEffect 不适用于获取数据 [重复]
【发布时间】:2021-08-13 01:54:48
【问题描述】:

这是代码sn-p:

  useEffect(() => {
    async function fetchData() {
      const url = 'https://api.randomuser.me';
      const response = await fetch(url);
      console.log('response: ', response);
    }
    fetchData();
  }, []); 

如您所见,它是一个 useEffect 挂钩,为某些数据调用公共 API,使用 async await 以等待响应。

但记录的数据不包含应有的内容。

这在 console.log 中:

body: ReadableStream
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://api.randomuser.me/"
__proto__: Response

怎么了?

【问题讨论】:

  • 添加await response.json()获取数据。
  • 这是一个Response 对象。

标签: javascript reactjs async-await react-hooks fetch


【解决方案1】:

您需要将响应解析为 JavaScript 对象,使用 response.json()


  useEffect(() => {
    async function fetchData() {
      const url = 'https://api.randomuser.me';
      const response = await fetch(url);
      const result = await response.json()
      console.log('result: ', result); // this the actual json response
    }
    fetchData();
  }, []); 

【讨论】:

    猜你喜欢
    • 2021-11-20
    • 2021-06-06
    • 1970-01-01
    • 2021-05-06
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 2019-07-01
    相关资源
    最近更新 更多