2015-10-26 36 views
2

我正在創建一個Web應用程序,它將根據用戶點擊的城市對OpenWeather API進行AJAX調用以獲取城市的天氣數據。使用React.js運行AJAX調用 - 使用React.js

我對我的前端Node.js/Express使用了React作爲我的後端 - 但是在實現基於用戶點擊進行API調用的正確設置時遇到了困難。

我該如何重構我的代碼以便將它基於點擊?

這是我到目前爲止(JSBIN:http://bit.ly/1WedsL2) - 這是硬編碼爲「倫敦」的時刻:

var data = [ 
    {name: "London"}, 
    {name: "Tokyo"}, 
    {name: "NYC"} 
]; 

var MusicBox = React.createClass({ 
    render: function() { 
     return (
      <div className="musicBox"> 
       <h1>This is the music box</h1> 
       <CityList data={this.props.data} /> 
      </div> 
     ); 
    } 
}); 

var CityList = React.createClass({ 
    getInitialState: function() { 
     return {data: []}; 
    }, 
    componentDidMount: function() { 
     $.ajax({ 
      url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=bd82977b86bf27fb59a04b61b657fb6f', 
      method: 'GET', 
      success: function(result) { 
       this.setState({data: result}); 
      }.bind(this) 
     }); 
    }, 
    render: function() { 
     var cityNodes = this.state.data.map(function(city) { 
      return (
       <City info={city} /> 
      ); 
     }); 
     return (
      <div className="cityList"> 
       {cityNodes} 
      </div> 
     ); 
    } 
}); 

var City = React.createClass({ 
    render: function() { 
     return (
      <div className="city"> 
       <h2 className="cityName"> 
        {this.props.info.name} 
       </h2> 
       {this.props.children} 
      </div> 
     ); 
    } 
}); 

var CityInfo = React.createClass({ 
    getInitialState: function() { 
     return {data: {}}; 
    }, 
    componentDidMount: function() { 
     $.ajax({ 
      url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=bd82977b86bf27fb59a04b61b657fb6f', 
      method: 'GET', 
      success: function(result) { 
       this.setState({data: result}); 
      }.bind(this) 
     }); 
    }, 

    render: function() { 
     return (
      <div> 
       <h3>{this.state.data.name}</h3> 
      </div> 
     ); 
    } 
}); 


ReactDOM.render(
    <MusicBox data={data} />, 
    document.getElementById('content') 
); 
+0

你在哪裏做檢查的點擊? –

回答

4

你想要做的是有一個按鈕,用戶可以點擊。這將用於您的ajax請求,而不是在componentDidMount中。

在渲染中添加一個按鈕

<button onClick={this.loadCityInfo} data-city={this.props.info.name}>{this.props.info.name}</button> 

你的函數應該是這樣的

loadCityInfo: function(e){ 
    var city = $(e.currentTarget).data('city'); 
    // now make your ajax request with the city's name passed to pull out the correct data 
} 
+0

謝謝約翰 - 我重構了我的代碼,爲您所提到的City Info組件中的每個城市添加按鈕。截至目前 - 我沒有更多的錯誤,但是我的頁面沒有渲染城市名稱,也沒有進行API調用......我錯過了其他的東西嗎? http://bit.ly/1PQcTHk – codinginnewyork

+0

@YNinNY所以我看到的第一件事就是你沒有在任何地方使用CityInfo ..而你的其他jsbin也沒有加載任何東西。你確定你正確設置它嗎? –

+0

@YNinNY看着你的jsbin,你有一些語法錯誤。想讓我看看嗎? –