2017-04-04 156 views
0

我正在嘗試製作具有反應的天氣應用程序,並且我想通過在input中輸入城市的name來更改城市。我有一個必須改變的狀態函數:ReactJS更改網址

update(e){ 
     this.setState({cityName: e.target.value}) 
    } 

而在渲染功能,我有這樣的:

return <div id="layout-content" className="layout-content-wrapper"> 
        <input type="text" 
        onChange={this.update.bind(this)}/> 
        <div className="panel-list">{ persons }</div> 
        <h1>{this.state.coord.lon}</h1> 
        <h1>{this.state.cityName}</h1>  //output my city name 

而且我有函數,我通過我的城市名稱中的var網址API:

UserList(city = this.state.cityName){ 
     let apiKey = 'c24bda9c5812d6be82860b70c35d41a5'; 
     let url = 'http://api.openweathermap.org/data/2.5/weather?q='; 
     let weatherURL = 'http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=c24bda9c5812d6be82860b70c35d41a5'; 
    return $.getJSON(weatherURL).then((response) => { 
     this.setState({coord: response.coord}); 
     this.setState({person: response.weather}); 
    }); 
    } 
     </div> 

但它不改變天氣預報。爲什麼它沒有改變? 所有代碼:

class App extends React.Component { 
    constructor(props){ 
    super(); 
    this.state = { 
     person: [], 
     coord: [], 
     cityName: 'London' 
    }; 
    } 

    componentDidMount() { 
     this.UserList(); 
    } 

    update(e){ 
     this.setState({cityName: e.target.value}) 
    } 

    UserList(city = this.state.cityName){ 
     let apiKey = 'c24bda9c5812d6be82860b70c35d41a5'; 
     let url = 'http://api.openweathermap.org/data/2.5/weather?q='; 
     let weatherURL = 'http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=c24bda9c5812d6be82860b70c35d41a5'; 
    return $.getJSON(weatherURL).then((response) => { 
     this.setState({coord: response.coord}); 
     this.setState({person: response.weather}); 
    }); 
    } 

    render() { 
     const persons = this.state.person.map((item) => { 
      return <div> 
       <h1>{item['id']}</h1> 
       <span>{item['main']}</span> 

      </div> 
     }); 

     return <div id="layout-content" className="layout-content-wrapper"> 
        <input type="text" 
        onChange={this.update.bind(this)}/> 
        <div className="panel-list">{ persons }</div> 
        <h1>{this.state.coord.lon}</h1> 
        <h1>{this.state.cityName}</h1> 
     </div> 
    } 
} 

export default App; 

回答

4

componentDidMount纔會被調用在組件的生命週期一次 - 右後分量被初始安裝。如果你希望你的update方法觸發UserList,你需要你的setState電話後打電話到UserList完成了update

update(e){ 
    this.setState({cityName: e.target.value},() => { 
    this.UserList(this.state.cityName); 
    }); 
} 

您還可以通過在componentDidUpdate檢查上一個/當前狀態做到這一點。請注意,如果你採取這種方法:如果你更新cityName狀態項在UserList它會導致無限循環。

componentDidUpdate(prevProps, prevState) { 
    if (prevState.cityName !== this.state.cityName) { 
     this.UserList(this.state.cityName); 
    } 
}