我正在使用 ReactJS 创建一个天气应用程序,并将 API 数据存储在状态中,但最终我在执行此操作时创建了越来越多的变量。
// Address
const [address, setAddress] = useState('')
//Conditions
const [conditions, setConditions] = useState('')
// Temperature
const [temperature, setTemperature] = useState('')
//Windspeed
const [windSpeed, setWindSpeed] = useState('')
//Wind dirrection
const [windDirection, setWindDirection] = useState('')
// Time
const [time, setTime] = useState('')
// Description
const [description, setDescription] = useState('')
// Temp high
const [tempHigh, setTempHigh] = useState('')
// Temp low
const [tempLow, setTempLow] = useState('')
有没有办法将 axios get 请求存储在单个变量中,并且只使用像
{results.data.weatherinfo}
这样的值或类似的值?
您可以将它们分组为单一状态,如下所示:
const [weatherDetails, setWeatherDetails] =
useState({
address: '',
conditions: '',
temperature: '',
windSpeed: '',
windDirection:'',
// ... and other variables
});
更多关于如何更改状态的信息,您可以参考这里
是的,您确实可以通过将 API 响应存储在单个对象中而不是每条数据的单独变量来简化状态管理。以下是实现这一目标的方法:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const WeatherApp = () => {
const [weatherData, setWeatherData] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('your-api-endpoint');
setWeatherData(response.data);
} catch (error) {
console.error('Error fetching weather data:', error);
}
};
fetchData();
}, []);
return (
<div>
{weatherData && (
<div>
<p>Address: {weatherData.address}</p>
<p>Conditions: {weatherData.conditions}</p>
<p>Temperature: {weatherData.temperature}</p>
<p>Wind Speed: {weatherData.windSpeed}</p>
<p>Wind Direction: {weatherData.windDirection}</p>
<p>Time: {weatherData.time}</p>
<p>Description: {weatherData.description}</p>
<p>Temp High: {weatherData.tempHigh}</p>
<p>Temp Low: {weatherData.tempLow}</p>
</div>
)}
</div>
);
};
export default WeatherApp;
在此方法中:
weatherData
来存储从 API 获取的所有天气信息。useEffect
钩子中,我们发出 axios 请求来获取天气数据并将其存储在 weatherData
状态中。weatherData
不为空时,我们才使用条件渲染来显示天气信息。这有助于避免在获取数据之前出现渲染错误。weatherData
的各个属性(例如,weatherData.address
、weatherData.conditions
等)来显示天气信息。这种方法简化了您的状态管理,并使您的代码更干净且更易于维护。