首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从天气api和setState中获取天气。

从天气api和setState中获取天气。
EN

Stack Overflow用户
提问于 2020-07-10 20:13:09
回答 1查看 130关注 0票数 0

这是我的州。我想从state中的所有对象中获取latlong,并获取它们的当前天气,然后将它们的temperature设置为温度状态。有谁能帮我一下吗?

代码语言:javascript
复制
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
                    }));
                    })
                }
              }
    }
EN

回答 1

Stack Overflow用户

发布于 2020-07-10 21:19:19

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

代码语言:javascript
复制
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});
      })
   }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62834057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档