我正在創建一個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')
);
你在哪裏做檢查的點擊? –