當我在文本框輸入郵編并不現實,只會顯示我最初在this
.state.zipcode里的27403這個郵編的城市,并且怎么我想用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=https://bbs.csdn.net/topics/>{ 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=https://bbs.csdn.net/topics/{this.state.value} onChange={this.handleChange} placeholder="Zip Code"/>
</div>
)
}
handleChange(event) {
this.setState(
{zipcode: event.target.value}
);
}
}
export default App;
uj5u.com熱心網友回復:
增加一個componentShouldUpdate鉤子函式,函式里面呼叫獲取天氣的方法轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/65618.html
標籤:JavaScript
上一篇:DW CC 2015 不顯示inlcude的檔案了?
下一篇:vue換行
