简体   繁体   English

我从 Api 获取数据,但是当我尝试使用 useState 设置值时,它给了我一个空的 object

[英]I get data from Api but when I try to set the value with useState it give me an empty object

Hello everyone newbie here, I'm trying to use UseState hook to set setForecastData to the result that I receive from the API call.大家好这里的新手,我正在尝试使用 UseState 挂钩将 setForecastData 设置为我从 API 调用收到的结果。 so then I will be able to access to it and use it elsewhere.这样我就可以访问它并在其他地方使用它。 After I set a new value to the hook I try to console?log it and it still give me an empty object!在我为钩子设置一个新值后,我尝试控制台?记录它,它仍然给我一个空对象! I don't know what Im doing wrong in here ?我不知道我在这里做错了什么? any suggestion is appreciate thanks!任何建议都非常感谢! ( please see comments on code ) (请参阅代码注释)

import axios from "axios";
import "./App.css";
import HomePage from "./Components/HomePage";
import MainPage from "./Components/MainPage";
const App = () => {
  const apiKey = process.env.REACT_APP_API_KEY;
  const [input, setInput] = useState("");
  const [city, setCity] = useState("");
  const [matchesArray, setMatchesArray] = useState([]);
  const [locationData, setLocationData] = useState();
  const [forecastData, setForecastData] = useState({});
  //get today weather info
  const getCurrentWeather = () => {
    axios
      .get(
        `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&APPID=${apiKey}`
      )
      .then((res) => {
        console.log(res.data);
        let resp = res.data;
        setLocationData(resp);
      })
      .catch((err) => console.log(err));
  };

  //get weekly weather info
  const getWeeklyWeather = () => {
    let lat = matchesArray[0].lat;
    let lon = matchesArray[0].long;
    axios
      .get(
        `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude=minutely,current&units=metric&appid=${apiKey}`
      )
      .then((res) => {
        const utcOffset = res.data.timezone_offset;
        const hourly = res.data.hourly;
        const daily = res.data.daily;
        let hourlyReduced = hourly.map((hour, index) => ({
          id: index,
          temp: hour.temp,
          weatherCondition: hour.weather[0].main,
          weatherIcon: hour.weather[0].icon,
        }));
        hourlyReduced = hourlyReduced.slice(0, 24);
        const dailyReduced = daily.map((day, index) => ({
          id: index,
          minTemp: day.temp.min,
          maxTemp: day.temp.max,
          weatherCondition: day.weather[0].main,
          weatherIcon: day.weather[0].icon,
        }));

        const forecastInfo = {
          utcOffset: utcOffset,
          hourlyForecast: hourlyReduced,
          dailyForecast: dailyReduced,
        };
        setForecastData(forecastInfo); // NOT WORKING
        console.log(forecastData); // this is not working! it show me an empty object
        console.log(hourlyReduced); // this work fine and it show the result
        console.log(dailyReduced); // this work fine and it show the result
        
        return forecastInfo;
      });
  };
  

  return (
    <div className="App">
      <HomePage
        input={input}
        setInput={setInput}
        city={city}
        setCity={setCity}
        matchesArray={matchesArray}
        getCurrentWeather={getCurrentWeather}
        setMatchesArray={setMatchesArray}
        getWeeklyWeather={getWeeklyWeather}
        locationData={locationData}
        forecastData={forecastData}
      />
      <MainPage locationData={locationData} forecastData={forecastData} />
    </div>
  );
};

export default App;

useState hooks are asynchronous. useState 挂钩是异步的。 Logging forecastData right after calling setForecastData will not guarantee that the hook has finished updating the state. Use a useEffect hook to log forecastData whenever it changes.在调用setForecastData后立即记录forecastData并不能保证挂钩已完成更新 state。使用 useEffect 挂钩在forecastData更改时记录它。

useEffect(() => {
  console.log(forecastData)
}, [forecastData])

暂无
暂无

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

相关问题 我从 API 获取数组,但是当我尝试在表中显示它时它显示空数组(noob ReactJs) - I GET array from API but when i try show it in the table it show me empty array (noob ReactJs) 我想将从 firestore 中获取的数据设置为 useState 的初始值 - I want to set the fetched data from firestore as initial value of useState 尝试从标签获取数据时获取未定义的值 - Getting an undefined value when I try to get data from a label firestore:当我尝试按日期获取数据时,数组为空 - firestore: array empty when i try to get data by date 我不断收到 [object Object]。 当我尝试从 map 函数获取数据时 - I keep getting [object Object]. when I try to get data from the map function 当我尝试从“/api/products”获取数据时,为什么会出错? - Why do I get an error when I try to get data from “/api/products”? 当我尝试将 Object 从 api 添加到我的 mongodb atlas db NODE.JS 时,我变得不确定 - I get undefined when i try to add an Object from an api to my mongodb atlas db NODE JS 当我尝试从属性值获取HTML数据时,为什么会出现错误? - Why do I get an error when I try to get HTML data from an attribute value? 尝试在其上使用错误的api时可以让Set / Map打我吗? - can I make Set/Map slap me when I try to use the wrong api on them? 当api在react js中使用axios成功时,我可以使用多个useState并设置数据吗? - Can I use multiples useState and set data when api's got success using axios in react js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM