首页 > 解决方案 > 通过 React 传递 API 数据

问题描述

我有一个函数getData()可以获取当前天气状况的 JSON 对象。虽然我可以在控制台中看到 JSON 对象,但我似乎无法将它传递给可用变量。我在这里想念什么?

    const getData = () => {
      let url = `https://api.openweathermap.org/data/2.5/weather?q=Asheville&appid=${key}`
      fetch(url)
          .then((response) => {
            return response.json();
          })
          .then((response) => {
             console.log(response);
          })
          .catch((err) => {
            console.log(err);
          })
    }

    function App() {
      let data = getData();
      console.log(data);
      return (
        <div className="App">
          <Forecast />
        </div>
      );
    }

我已经尝试了几种方法,但无法正常工作。同样由于某种原因,它两次登录控制台,我不知道为什么。任何意见是极大的赞赏!

标签: javascriptreactjsapifetch

解决方案


你可以使用反应钩子

const useGetData = () => {
  const [data, setData] = React.useState(null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    let url = `https://api.openweathermap.org/data/2.5/weather?q=Asheville&appid=${key}`;
    fetch(url)
      .then((response) => response.json())
      .then((response) => setData(response))
      .catch((err) => setError(err));
  }, []);

  return [data, error];
};

function App() {
  let [data, error] = useGetData();

  return (
    <div>
      <p>{JSON.stringify(data, null, 2)}</p>
      {error && <p>There's been an error: {error}</p>}
    </div>
  );
}


推荐阅读