从weather-api和setState-inoto中的对象数组获取weather



这是我的状态。我想从state中的所有对象中获取latlong,并获取它们的当前天气,然后将它们的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
}));
})
}
}
}

尽管在for循环中使用fetch请求从来都不是一个好主意,因为元素的数量会增加,但会有很多到服务器的fetch请求,这最终会使进程变慢。不过,如果你想这样做,请尝试下面描述的代码:

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 => {
// 1. Make a shallow copy of the items
let items = [...this.state.data];
// 2. Make a shallow copy of the item you want to mutate
let item = {...items[1]};
// 3. Replace the property you're intested in
item.temperature = data.main.temp;
// 4. Put it back into our array. N.B. we *are* mutating the array here, but that's why we made a copy first
items[1] = item;
// 5. Set the state to our new copy
this.setState({items});
})
}

最新更新