我从 Api 获取数据,但是当我尝试使用 useState 设置值时,它给我一个空对象
I get data from Api but when I try to set the value with useState it give me an empty object
各位新手大家好!我正在尝试使用 UseState 挂钩将 setForecastData 设置为我从 API 调用收到的结果,这样我就可以访问它并在其他地方使用它。
在我为钩子设置一个新值后,我尝试 console.log 它,它仍然给我一个空对象!
我不知道我在这里做错了什么?任何建议都非常感谢!
(请参阅代码注释)
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])
各位新手大家好!我正在尝试使用 UseState 挂钩将 setForecastData 设置为我从 API 调用收到的结果,这样我就可以访问它并在其他地方使用它。 在我为钩子设置一个新值后,我尝试 console.log 它,它仍然给我一个空对象! 我不知道我在这里做错了什么?任何建议都非常感谢! (请参阅代码注释)
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])