我正在研究一个Webstie,该Webstie可以使用免费的天气API显示城市天气。我不知道如何获取用户的邮政编码

问题描述 投票:0回答:2
import React from 'react';

import './App.css';
const apiKey = '53df5b52f003d1bd1df16a7f6f299393';
const zipcode = '98107';

class App extends React.Component{//初始化值
       constructor(){
       super();
      this.state={

       weather:null,

      }


}

async componentDidMount(){   //获取天气
  const weather=await this.fetchWeather();
      this.setState(
        {
          weather,

        }
      );
      console.log(weather)


}

fetchWeather=async () =>{// 读取天气

     return await fetch(`http://api.openweathermap.org/data/2.5/forecast?zip=98107&appid=53df5b52f003d1bd1df16a7f6f299393`).then(data=>{ return data.json();})

}//api.openweathermap.org/data/2.5/weather?zip=${zipcode}&appid=${apiKey}`



  render(){


    const list = () => {
      let {weather}=this.state;
      const res = [];
      for(let i = 0; i < weather.list.length; i++) {
        res.push(<li key={i}> <span className="colorFont">第{i+1}天  </span>  {weather.list[i].main.temp}</li>)
      }
      return res
    }


    if(!this.state.weather){
      return null;
    }


    let {weather}=this.state;

        return(

            <div className="App">
              <h2> {weather.city.country}  {weather.city.name}  {weather.cnt} 天未来天气预测</h2>
            <ul className="deteleUnderLine">

           {list()  }   {/*调用函数释*/}
            </ul>


          </div>


        )

  }

}
export default App;

我是font = tend学习者的新手,我正在使用REACT。这是一个网站,可以显示未来40天的城市天气。我希望用户添加其邮政编码,然后显示其天气。我对如何设置像输入标签来获取用户的值感到困惑。我认为,当我从用户那里获得价值时,我需要在此更新邮政编码]

http://api.openweathermap.org/data/2.5/forecast?zip=98107&appid=53df5b52f003d1bd1df16a7f6f299393。我尝试放入输入标签,但我不怎么做。

javascript html reactjs
2个回答
0
投票

输入标签很简单

<input id=zip> />

然后执行一个onkeyup处理程序以检查其完成时间,然后将其放入weather API中。一起:

zip.placeholder = "Enter your zip code, if you want to know the weather!!!!"
zip.onkeydown = e => 
  e
  .target
  .value
  .length > 4 && 
  e.keyCode != 8 &&
  (
    e.preventDefault()
  );

zip.onkeyup = e => 
  e
  .target
  .value
  .length > 4 &&
  fetch(
    "https://api.openweathermap.org/data/2.5/forecast?zip=" 
    + e.target.value 
    + "&appid=53df5b52f003d1bd1df16a7f6f299393"
  )
  .then(r => r.json())
  .then(r => 
    weatherInfo.innerHTML = JSON.stringify(r,0,4)
  );
#zip {
  width:365px
}
<input id=zip  />
<pre id=weatherInfo></pre>

0
投票

您可以使用浏览器的地理位置和某些API(例如Google Maps来尝试找出用户的邮政编码。

在这里查看此解决方案:https://coderwall.com/p/joqisq/get-users-zip-code-using-google

也有一些API使您可以立即使用邮政编码,但其中大多数仅适用于特定国家/地区。

© www.soinside.com 2019 - 2024. All rights reserved.