【问题标题】:Fetching data and using the state hook获取数据并使用状态钩子
【发布时间】:2020-11-26 01:41:21
【问题描述】:

我正在尝试从 api 获取数据并将该数据用作useState 钩子的状态。

fetch('https://blockchain.info/ticker') // Call the fetch function passing the url of the API as a parameter
  .then((resp) => resp.json()) // Transform the data into json
.then(function(resp) {
    setData({data: resp.json()})
    console.log(data)

当我运行以下命令时,我收到此错误Unhandled Rejection (TypeError): resp.json is not a function 我猜我没有正确获取数据,因为我已经很长时间没有这样做了。
我尝试了以下 setData({data: resp}) 它让我的浏览器崩溃了。
我知道我在某个地方犯了一个简单的新手错误,所以任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 您已经在第一个 .then 回调中将其转换为 JSON。现在它只是 JSON,您需要做的就是使用它。至于使您的浏览器崩溃,这是您需要解决的问题。是什么导致崩溃?您在哪里进行此 fetch 调用?
  • 你的用户名????????
  • 我在 return 语句之前的 function() 下进行了 fetch 调用。这是完整的页面。 github.com/Imstupidpleasehelp/bitcoinTracker/blob/main/src/…

标签: javascript reactjs api


【解决方案1】:

在您的 github 代码中发现了一些问题。请在下面尝试。

import React, { useState, useEffect } from 'react';

const Bitcoin = () => {
  const [data, setData] = useState({});

  useEffect(() => {
    fetch('https://blockchain.info/ticker') // Call the fetch function passing the url of the API as a parameter
      .then((resp) => resp.json()) // Transform the data into json
      .then((resp) => {
        console.log(resp);
        setData(resp);
      });
  }, []);

  return (
    <div className="App">
      <header className="App-header"></header>
    </div>
  );
};

export default Bitcoin;

【讨论】:

  • 谢谢。我事先只用类组件完成了这项工作。虽然有 1 个小问题,但我收到以下错误 Uncaught (in promise) TypeError: Failed to fetch 这是 api 的问题吗?还是在我这边?
  • 我可以在代码沙箱上运行它 - codesandbox.io/s/prod-bash-s8xur?file=/src/App.js
【解决方案2】:

fetch('https://blockchain.info/ticker').then(resp =&gt; {resp.json() setData(resp)}).catch(err=&gt; console.log(err))); 使用异步等待。它更短,也不会令人困惑。在该代码中,您不需要链接另一个 .then。你得到的响应下一步就是将数据设置为你的钩子函数就像这样

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 2023-01-03
    • 2021-06-06
    相关资源
    最近更新 更多