我遵循这个例子:https://reactjs.org/docs/faq-ajax.html
但是我的代码是返回的,weather.map不是函数吗?
function App(props) {
const [weather, setWeather] = useState([]);
useEffect(() => {
fetch("https://api.openweathermap.org/data/2.5/weather?q=kalamazoo&appid=XXXXXXXXXXXX")
.then(res => res.json())
.then(
(result) => {
setWeather(result)
console.log(result)
}
)
},[])
return (
<div className="App">
{weather.map(item => (
<li key={item.id}>{item.main}</li>
))}
</div>
);
}
export default App;
我知道它需要一个数组,但是即使API没有返回,我仍然会得到错误。
发布于 2022-05-06 21:53:35
openweathermap /weather API返回一个对象。您可以查看他们的昂首阔步,了解APIs的详细信息及其确切的响应格式。
要访问天气信息,您需要执行以下操作:
useEffect(() => {
fetch(
'https://api.openweathermap.org/data/2.5/weather?q=kalamazoo&appid=XXXXXXXXXXXX'
)
.then((res) => res.json())
.then((result) => {
setWeather(result.weather); // this is where weather data array is present
console.log(result);
});
}, []);
发布于 2022-05-06 22:05:36
映射不是函数错误意味着weather
数据类型不是数组,因此它没有映射函数,API返回对象,所以可以使用直接映射代替
Object.values(weather || {}).map((item)=>{
return(
<li key={item.id}>{item.main}</li>
)
})
https://stackoverflow.com/questions/72147663
复制相似问题