在小型天气应用程序中使用 axios.get () 而不是 fetch() 时,我遇到了状态从未更新且应用程序未重新渲染的问题

问题描述 投票:0回答:2

我正在使用 React 开发一个小型天气应用程序作为练习,我的目标是更好地使用 Axios,因为它是我实习的公司所需的 HTTP 客户端,但我运行时遇到了问题。让我告诉你:

import React, { useState } from "react";
import axios from "axios";

const Api = {
  apiKey: "",
  baseURL: "https://api.openweathermap.org/data/2.5/",
};

function App() {
  const [query, setQuery] = useState("");
  const [weather, setWeather] = useState({});

  function Search(e) {
    if (e.key === "Enter") {
      fetch(
        `${Api.baseURL}/weather?q=${query}&units=metric&appid=${Api.apiKey}`
      )
        .then((res) => res.json())
        .then((result) => {
          setWeather(result);
          setQuery("");
        });
    }
  }
  
  // function Search(e) {
  //   if (e.key === "Enter") {
  //     axios
  //       .get(
  //         `${Api.baseURL}/weather?q=${query}&units=metric&appid=${Api.apiKey}`
  //       )
  //       .then((result) => {
  //         setWeather(result);
  //         setQuery("");
  //       })
  //       .catch((error) => console.log(error));
  //   }
  // }


  function handleChange(e) {
    setQuery(e.target.value);
  }

  function dateBuilder(d) {
    let months = [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December",
    ];
    let days = [
      "Sunday",
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday",
    ];
    let day = days[d.getDay()];
    let date = d.getDate();
    let month = months[d.getMonth()];
    let year = d.getFullYear();

    return `${day} ${date} ${month} ${year}`;
  }
  return (
    <div
      className={
        typeof weather.main != "undefined"
          ? weather.main.temp > 16
            ? "container warm"
            : "container"
          : "container"
      }
    >
      <div className="search-area">
        <input
          type="text"
          className="search-bar"
          placeholder="Search by city name (Ex: Paris)"
          onChange={handleChange}
          onKeyPress={Search}
          value={query}
        />
      </div>
      {typeof weather.main != "undefined" ? (
        <div>
          <div className="location-box">
            <div className="location">
              {weather.name},{weather.sys.country}
            </div>
            <div className="date"> {dateBuilder(new Date())}</div>
          </div>

          <div className="weather-box">
            <div className="temp">{Math.round(weather.main.temp)}°C</div>
            <div className="weather">{weather.weather[0].main}</div>
          </div>
        </div>
      ) : (
        ""
      )}
    </div>
  );
}

export default App;

正如你所看到的,我使用 fetch() 解决了这个问题(我在网上查了一下,有人使用 fetch 做了一个类似的应用程序,所以我尝试了它,它工作了,我不知道为什么它真的工作了),正如你在我渲染之前看到的那样我的应用程序的一部分使用三元运算符,我正在检查 if (weather.main != undefined),所以我确保 api 调用返回,并且 setWeather 强制做出反应以重新渲染并更新状态。但是,当使用 axios.get 使用注释的搜索功能时,api 调用成功,我可以在控制台中看到它,但weather.main 始终解析为未定义,我觉得应用程序没有重新渲染,我在网上检查了每个人都说该应用程序没有更新状态并重新渲染,但我不知道如何修复它。 任何帮助将非常感激, 谢谢你, 和平。

javascript reactjs axios openweathermap
2个回答
0
投票

axios
将异步调用的结果包装在对象内。 您可以访问数据对象内的结果。

axios.get(url)
   .then(res => res.data)

-1
投票
const getApiRes=asnyc(url)=> {
   try{
    const result=await axios.get(url)
    return result
    }
    catch(error){
    console.log(error)
    }
}
    
    function Search(e) {
        if (e.key === "Enter") {
         const result=getApiRes(url)
        }
      }
© www.soinside.com 2019 - 2024. All rights reserved.