简体   繁体   English

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

[英]When using axios.get () instead of fetch() in a small weather app i am having problems where the state is never updated and the app not re-rendered

I am Developping a small weather app using react as practice and i am aiming at getting better at using Axios for it is the desired HTTP client at the company where i am doing an internship but i am running with a problem.我正在开发一个使用 react 作为实践的小型天气应用程序,我的目标是更好地使用 Axios,因为它是我正在实习的公司所需的 HTTP 客户端,但我遇到了问题。 Let me show you:让我演示给你看:

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;

As you can see i fixed the problem using fetch() (i checked online and someone did a similar app using fetch so i tried it and it worked i dont know why it really worked), and as you can see before i render a part of my app using the terniary operator i am checking if (weather.main != undefined) so i am make sure the api call returned and setWeather forced react to rerender adn update the state.正如你所看到的,我使用 fetch() 修复了这个问题(我在网上查了一下,有人使用 fetch 做了一个类似的应用程序,所以我尝试了它并且它有效,我不知道它为什么真的有效),正如你在渲染一部分之前所看到的在使用三元运算符的应用程序中,我正在检查 (weather.main != undefined) 是否 (weather.main != undefined) 所以我确保 api 调用返回并且 setWeather 强制响应重新渲染和更新状态。 But when using the commented Search function using axios.get the api call is succesfull i can see it in my console but the weather.main is always resolved to undefined and i feel like the app is not re-rendering, i checked online everyone says that the app is not updating the state and re-rendering but i did not know how to fix it.但是,当使用 axios.get 使用注释的搜索功能时,api 调用成功了,我可以在控制台中看到它,但是 weather.main 总是解析为未定义,我觉得应用程序没有重新渲染,我在网上查了一下,每个人都说该应用程序没有更新状态和重新渲染,但我不知道如何修复它。 Any help would be much appreciated, Thank you, Peace.任何帮助将不胜感激,谢谢,和平。

axios wraps the result of the asynchronous call inside an object. axios将异步调用的结果包装在一个对象中。 You could get access to the result inside the data object.您可以访问数据对象内的结果。

axios.get(url)
   .then(res => res.data)
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)
        }
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM