簡體   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

大家好這里的新手,我正在嘗試使用 UseState 掛鈎將 setForecastData 設置為我從 API 調用收到的結果。 這樣我就可以訪問它並在其他地方使用它。 在我為鈎子設置一個新值后,我嘗試控制台?記錄它,它仍然給我一個空對象! 我不知道我在這里做錯了什么? 任何建議都非常感謝! (請參閱代碼注釋)

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 掛鈎是異步的。 在調用setForecastData后立即記錄forecastData並不能保證掛鈎已完成更新 state。使用 useEffect 掛鈎在forecastData更改時記錄它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM