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

当我输入邮编,并不起作用,只会显示,我在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;


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

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

    //触发 fetchWeather 方法。

https://www.ctolib.com/willluck-react-base-staging-weather.html