大家好,这里的新手!我试图使用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并不能保证钩子已经完成状态更新.使用useEffect钩子记录forecastData的变化.

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

Javascript相关问答推荐

Promise.all立即跳到那时,而不是调用所有Promise

自定义帖子类型帖子未显示在网站上

如何循环访问对象数组并以关键值形式获得结果?

如何使用JavaScript用等效的功能性HTML替换标记URL格式?

格式值未保存在redux持久切片中

浮动Div的淡出模糊效果

如何修复我的js构建表每当我添加一个额外的列作为它的第一列?

我们如何从一个行动中分派行动

构造HTML表单以使用表单数据创建对象数组

使用GraphQL查询Uniswap的ETH价格

我的角模板订阅后不刷新'

Reaction组件在本应被设置隐藏时仍显示

按下单键和多值

使用Ace编辑器对子组件实例的native-element 进行Angular 获取时面临的问题

如何在Press上重新启动EXPO-AV视频?

JS Animate()方法未按预期工作

如何修复使用axios运行TSC index.ts时出现的错误?

在SuperBase JS客户端中寻址JSON数据

如何在尚未创建的鼠标悬停事件上访问和着色div?

如何使用Reaction路由导航测试挂钩?