2017-04-04 11 views
0

私は反応して天気のアプリを作ろうとしていますが、都市のnameinputに入力して都市を変更したいと思います。私は状態を変更しなければならない機能があります。ReactJSの変更URL

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 

をそして私は、APIへのURLの私の都市名VARを渡すところ、私は機能を持っている:

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は唯一のコンポーネントのライフサイクルでの1時間に呼び出されます - コンポーネントが最初にマウントされた直後。あなたはupdate方法はUserListをトリガしたい場合、あなたはsetState呼び出しの後UserListを呼び出す必要はあなたにもcomponentDidUpdateで前/現在の状態を検査することによって、これを達成することができupdate

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

で完了します。この方法をとる場合は、UserListcityName状態項目を更新すると、無限ループが発生します。

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