weixin_44528094
weixin_44528094
采纳率50%
2020-04-15 00:10

初学习react,本人弄了一个天气预测的网页,显示未来40天天气,我想让用户在文本框输入邮编,并且显示用户城市天气。

20

当我输入邮编,并不起作用,只会显示,我在this.state.zipcode设置的27403城市的天气, 另外如何用formap或者foreach 拿到数组

import React from 'react';

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


class App extends React.Component{//Initial value
       constructor(){
       super();
      this.state={
       zipcode:'27403',

       weather:null,


      }
      this.handleChange  = this.handleChange.bind(this); 

}

async componentDidMount(){   //get weather data
  const weather=await this.fetchWeather();
      this.setState(
        {
          weather,

        }
      );
      console.log(weather)


}

fetchWeather=async () =>{// reading weather data

     return await fetch(`http://api.openweathermap.org/data/2.5/forecast?zip=${this.state.zipcode}&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">The{i+1}Day  </span>  {weather.list[i].main.temp}</li>)
      }
      return res
    }


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


    let {weather}=this.state;

        return(

            <div className="App">
              <h2> {weather.city.country}  {weather.city.name}  {weather.cnt} days weather forecast </h2>
            <ul className="deteleUnderLine">

           {list()  }   {/*调用函数释*/}
            </ul>
            <input type="text" value={this.state.value} onChange={this.handleChange} placeholder="Zip Code"/>

          </div>


        )

  }

handleChange(event) {
  this.setState(
    {zipcode: event.target.value}
    );
  }

}
export default App;


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • wojiushiwo945you 毕小宝 1年前

    这个 onChange 事件还需要再完善一下,设置 zipcode 后,还需要重新获取对应的天气信息,触发一下fetchWeather方法。

     this.setState(
        {zipcode: event.target.value}
        );
      }
    
        //触发 fetchWeather 方法。
    
    点赞 1 评论 复制链接分享
  • zqbnqsdsmd zqbnqsdsmd 1年前