Javascript 使用react组件和useEffect显示API中的数据
我有一个react组件,它每次呈现时都会显示通过道具接收的国家信息(国家),并且使用天气堆栈API也必须显示当前的首都天气。第一部分(显示来自道具的国家数据)工作正常,但我很难从天气API获取数据。我在控制台上看到我正在获取当前天气,但无法使用setState()将其分配给天气变量,因此我的应用程序崩溃 这是我到目前为止使用的组件代码,我尝试使用Javascript 使用react组件和useEffect显示API中的数据,javascript,reactjs,api,axios,Javascript,Reactjs,Api,Axios,我有一个react组件,它每次呈现时都会显示通过道具接收的国家信息(国家),并且使用天气堆栈API也必须显示当前的首都天气。第一部分(显示来自道具的国家数据)工作正常,但我很难从天气API获取数据。我在控制台上看到我正在获取当前天气,但无法使用setState()将其分配给天气变量,因此我的应用程序崩溃 这是我到目前为止使用的组件代码,我尝试使用async/await和。然后synataxis,以防我错售了一些东西,但总是得到相同的结果: const CountryDetails = async
async/await
和。然后
synataxis,以防我错售了一些东西,但总是得到相同的结果:
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>
</>
);
};
constcountrydetails=async({country})=>{
const[weather,setWeather]=useState({});
//const hook=async()=>{
//const result=等待axios.get(`http://api.weatherstack.com/current?access_key=${WEATHER\u API}&query=${country.capital}`);
//console.log(result.data);
//setWeather(result.data.current);
//控制台.日志(天气);
// }
常量挂钩=()=>{
axios.get(`http://api.weatherstack.com/current?access_key=${WEATHER\u API}&query=${country.capital}`)。然后((响应)=>{
console.log('then');
塞特威瑟({
温度:响应。数据。当前。温度,
img:response.data.current.weather_图标,
风:响应。数据。当前。风速,
目录:response.data.current.wind\u direction
});
console.log(response.data.current);
});
}
useffect(hook,[]);
控制台.日志(天气);
返回(
{country.name}
首都{国家首都}
人口{国家人口}
语言
{country.languages.map((lang)=>{
- {lang.name}
;
})}
{国家首都}的天气
温度:{weather.current.temperature}
风:{天气.海流.风速}方向{天气.海流.风向}
);
};
完整代码的沙箱:您只是从天气状态中提取了错误的属性。这项工作:
import axios from "axios";
import { useState, useEffect } from "react";
const WEATHER_API = "xxx";
const CountryDetails = ({ country }) => {
const [weather, setWeather] = useState({});
const hook = () => {
axios
.get(
`http://api.weatherstack.com/current?access_key=${WEATHER_API}&query=${country.capital}`
)
.then((response) => {
console.log("then", response);
setWeather({
temperature: response.data.current.temperature,
img: response.data.current.weather_icons,
wind: response.data.current.wind_speed,
dir: response.data.current.wind_dir
});
console.log(JSON.stringify(weather));
});
};
useEffect(hook, []);
console.log(weather);
return (
<>
<h2>languages</h2>
<p><b>temperature: </b>{weather.temperature}</p>
<p>
<b>wind: </b>
{weather.wind} direction {weather.dir}
</p>
</>
);
};
export default function App() {
return (
<div className="App">
<CountryDetails country={{ capital: "London" }} />
</div>
);
}
从“axios”导入axios;
从“react”导入{useState,useffect};
const WEATHER_API=“xxx”;
const CountryDetails=({country})=>{
const[weather,setWeather]=useState({});
常量挂钩=()=>{
axios
.得到(
`http://api.weatherstack.com/current?access_key=${WEATHER\u API}&query=${country.capital}`
)
。然后((响应)=>{
console.log(“then”,response);
塞特威瑟({
温度:响应。数据。当前。温度,
img:response.data.current.weather_图标,
风:响应。数据。当前。风速,
目录:response.data.current.wind\u目录
});
log(JSON.stringify(weather));
});
};
useffect(hook,[]);
控制台.日志(天气);
返回(
语言
温度:{weather.temperature}
风:
{天气.风向}方向{天气.风向}
);
};
导出默认函数App(){
返回(
);
}
这是我创建的一个代码沙盒,用于处理您的代码。既然您声明您成功地从API接收了数据,我就用我的getWeather
函数模拟它。除了@Vieta回答的问题外,您提供的代码中还有其他问题。查看这是否有帮助,或者错误是否仍然存在,请提供该代码段的复制示例:
从“react”导入{useffect,useState};
const getWeather=(国家)=>{
还愿({
数据:{
当前:{
温度:“,
天气预报:,
风速:“,
署长:“”
}
}
});
};
const CountryDetails=({country})=>{
const[weather,setWeather]=useState({});
常量挂钩=()=>{
getWeather(国家)。然后((响应)=>{
console.log(“then”);
塞特威瑟({
温度:响应。数据。当前。温度,
img:response.data.current.weather_图标,
风:响应。数据。当前。风速,
目录:response.data.current.dir,
风速:response.data.current.wind\u speed
});
console.log(response.data.current);
});
};
使用效果(挂钩,[国家]);
//您应该在此处记录{},而不是未定义
控制台.日志(天气);
返回(
{country.name}
首都:{country.Capital}
人口:{国家人口}
语言文字
{/*在map函数的回调中没有返回任何内容*/}
{country.languages.map((lang,i)=>(
- {lang.name}
))}
{国家首都}的天气
温度:
{/*正如@Veit所提到的,您访问了错误的属性*/}
{天气温度}
风:
{天气.风速}方向:{weather.dir}
);
};
导出默认值(道具)=>{
常量国家={
语言:[{名称:'}],
国旗:“,
首都:“,
姓名:“,
人口:“
};
返回;
};
为什么组件的功能定义中有async
?删除它行吗?首先,我使用的是async/await语法,现在我已经删除了,但仍然不起作用。使用空对象初始化weather
,并尝试在jsx中访问它的属性。温度:{weather.current.temperature}这一行将在组件渲染时失败。我只是像您一样尝试,但仍然出现相同的错误,并且在显示console.log(weather)的行上。仍然返回未定义的。这就像setWeather它不工作一样。嗯,那么您应该检查一下