【发布时间】:2020-07-10 12:13:09
【问题描述】:
这是我的状态。我想从state 中的所有对象中获取lat 和long 并获取它们当前的天气,然后将它们的temperature 设置为温度状态。有人可以帮我解决这个问题吗?
class App extends React.Component{
this.state = {
data: [
{
id: 1,
lat: "35.6892" ,
long: "51.3890",
temperature: '',
},
{
id: 2,
lat: "45.6892" ,
long: "35.3890",
temperature: '',
},
{
id: 3,
lat: "59.6892" ,
long: "-72.3890",
temperature: '',
},
{
id: 4,
lat: "23.6892" ,
long: "-52.3890",
temperature: '',
},
componentDidMount() {
for(var i =0 ; i<= this.state.data.length - 1 ; i++) {
let url = 'https://api.openweathermap.org/data/2.5/weather?lat=' + this.state.data[i].lat + '&lon=' + this.state.data[i].long + '&units=metric&appid=api key';
fetch(url)
.then(response => response.json())
.then(data => {
this.setState.data((prevState, props) => ({
temperature: data.main.temp
}));
})
}
}
}
【问题讨论】:
标签: react-native fetch setstate weather-api