我是新来的反应者,我正在尝试练习在课程中学到的东西。我正在使用openweather api提供的weatherapp。我正在获得所有数据的响应,但是当我尝试显示它们时却无法正常工作。你能给我什么建议吗?
这是我的代码:
setSpanSizeLookup()
import React, { useState, useEffect } from 'react';
import './App.css';
import Weather from './Weather';
const App = () => {
const [weather, setWeather] = useState([]);
useEffect(() => {
getWeather();
}, []);
let lat;
let lon;
const getWeather = () => {
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(position => {
lon = position.coords.longitude;
lat = position.coords.latitude;
const APP_KEY = "e802333933a66ec7a7588d658785ad09";
const API = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&cnt=5&APPID=${APP_KEY}`;
fetch(API)
.then(response => {
return response.json();
})
.then(data => {
setWeather(data.list);
console.log(setWeather);
})
});
}
}
return (
<div className="App">
<div>
{weather.map(w => (
<Weather temperature={w.list.main} weather={w.list.weather.description}/>
))}
</div>
</div>
);
}
export default App;
答案 0 :(得分:0)
没有看到API返回的数据并且不知道状态的形状(请问您是否可以在问题中发布console.log输出),看来您需要这样做:
<Weather temperature={w.main} weather={w.weather.description}/>
在此处设置状态时,您已经在响应中破坏了列表属性:
.then(data => {
setWeather(data.list);
console.log(setWeather);
})
您还可以在渲染函数中放置console.log
来查看您要渲染的状态的形状。
据我所知,在通过状态映射时,在render方法中抛出了错误,就在这里:
<Weather temperature={w.list.main}
该元素上没有list
属性。
非常确定您可以在React中调试如下代码:
{
weather.map(w => {
console.log(w)
return <Weather temperature={w.list.main} weather={w.list.weather.description}/>
})
}