我想使用 Axios returns 从 API 获取的数据未定义

The data I want to get from API using Axios returns undefined

最近我开始接触 React,在练习时遇到了这个问题。我想从 API 中获取信息,然后在控制台上查看它,但它 returns 未定义。我想我弄错了 axios 但是我看不到它。

import axios from "axios";
import { useState } from "react";
import "./App.css";

function App() {
  const [place, setPlace] = useState("new york");
  const [placeInfo, setPlaceInfo] = useState({});

  const handleFetch = () => {
    const { data } = axios.get(
      `https://api.weatherapi.com/v1/forecast.json?key=931f75d818c34b51aca143737222202&q=${place}&days=1&aqi=no&alerts=no`
    );

    console.log(data);
  };

  return (
    <div className="App">
      <input
        type="text"
        value={place}
        onChange={(e) => {
          setPlace(e.target.value);
        }}
      ></input>
      <button onClick={handleFetch}>Search</button>
    </div>
  );
}

export default App;

您应该使用 async 函数和 awaiting 作为结果,如下所示:

  const handleFetch = async () => {
    const { data } = await axios.get(
      `https://api.weatherapi.com/v1/forecast.json?key=931f75d818c34b51aca143737222202&q=${place}&days=1&aqi=no&alerts=no`
    );

    console.log(data);
  };

否则你会得到 Promise 作为结果,并且由于 Promise 没有 data 字段,你会得到 undefined.