我正在 React 中创建一个 Web 应用程序,它需要处理 2 个 API 调用,其中一个调用依赖于另一个调用。第一个 API 调用将从 OpenWeather API 获取数据 - 然后第二个 API 调用将使用该回调数据来调用 Spotify 的 API。
如何在 React 中设置此嵌套/依赖 API 调用?我可以在第一个 API 调用的 success 函数下运行 ajax 调用吗?或者我是否需要创建一个处理第二个 API 的新组件,以便以某种方式从第一个 API 调用获取数据?
// Making the API call to OpenWeather API:
var CityInfo = React.createClass({
getInitialState: function() {
return {data: {}};
},
loadCityInfo: function(e){
var city = $(e.currentTarget).data('city');
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q='+city,
method: 'GET',
success: function(result) {
this.setState({data: result});
console.log(result);
}.bind(this)
});
},
render: function() {
return (
<div>
<h2><button onClick={this.loadCityInfo} data-city={this.props.info.name}>{this.props.info.name}</button></h2>
</div>
);
}
});
最佳答案
我建议您遵循通量模式来特别提出您的请求。但是,根据您所拥有的,您可以提出链接请求
var CityInfo = React.createClass({
loadCityInfo: function(e){
var city = $(e.currentTarget).data('city');
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q='+city+"&APPID=3c8e84ea9c6f7938384d3c3980033d80",
method: 'GET',
success: function(result) {
this.setState({data: result});
console.log(result);
// make request here
}.bind(this)
});
}
});
现在,除了使用 Flux 模式执行此操作的方法之外,还有一个执行请求的操作文件..
module.exports = {
loadWeather: function(city){
return $.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q='+city+"&APPID=3c8e84ea9c6f7938384d3c3980033d80",
method: 'GET'
});
},
loadSpotify: function(params){
//do request here
}
}
然后在你的 loadcity 函数中你可以这样做
loadCityInfo: function(e){
var city = $(e.currentTarget).data('city');
actions.loadWeather(city).done(function(res){
//set your state
actions.loadSpotify(params)
}).fail(funciton(res){
//handle fail
});
}
关于javascript - React.js 中的嵌套 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33376096/