【发布时间】:2021-02-08 10:45:25
【问题描述】:
我有这个反应组件,每次渲染时都会显示通过道具(国家)接收的国家信息,并且使用天气堆栈 API 还必须显示当前时间的首都天气。第一部分(显示来自道具的国家数据)工作正常,但我很难从天气 API 获取数据。我在控制台上看到我正在获取当前天气,但无法使用 setState() 将其分配给天气变量,因此我的应用程序崩溃了。
这是我到目前为止的组件代码,我尝试使用 async/await 和 .then 语法,以防我拼错了一些东西,但总是得到相同的结果:
const CountryDetails = async ({country}) => {
const [weather, setWeather] = useState({});
// const hook = async () => {
// const result = await axios.get(`http://api.weatherstack.com/current?access_key=${WEATHER_API}&query=${country.capital}`);
// console.log(result.data);
// setWeather(result.data.current);
// console.log(weather);
// }
const hook = () => {
axios.get(`http://api.weatherstack.com/current?access_key=${WEATHER_API}&query=${country.capital}`).then((response) => {
console.log('then');
setWeather({
temperature: response.data.current.temperature,
img: response.data.current.weather_icons,
wind: response.data.current.wind_speed,
dir: response.data.current.wind_direction
});
console.log(response.data.current);
});
}
useEffect(hook, []);
console.log(weather);
return (
<>
<h1>{country.name}</h1>
<p>capital {country.capital}</p>
<p>population {country.population}</p>
<h2>languages</h2>
<ul>
{country.languages.map((lang) => {
<li key={lang.name}>{lang.name}</li>;
})}
</ul>
<img src={country.flag}></img>
<h2>Weather in {country.capital}</h2>
<p><b>temperature: </b>{weather.current.temperature}</p>
<img src={weather.current.weather_icons} />
<p><b>wind: </b>{weather.current.wind_speed} direction {weather.current.wind_direction}</p>
</>
);
};
【问题讨论】:
-
为什么你的组件函数定义中有
async?删除它会起作用吗? -
首先我使用的是 async/await 语法,现在我已经删除了,但仍然无法使用
-
你用一个空对象初始化
weather并尝试在你的 jsx 中访问它的属性。渲染组件时,<p><b>temperature: </b>{weather.current.temperature}</p>行将失败
标签: javascript reactjs api axios