【发布时间】:2018-10-26 16:29:11
【问题描述】:
我正在开发一个 React 应用程序并发出 API 请求,我使用了 fetch(),但由于某些未知原因,fetch() 导致了多个 API 请求,而我只期待一个。
在当前情况下,我在浏览器的“网络”选项卡中收到 3 个请求:
负责相同的代码是:
componentDidMount() {
var planet_id = this.props.match.params.id;
let planetData = [];
apiFetch('planets', false, planet_id).then(function(jsonResponse) {
planetData = jsonResponse;
}).then(data => this.setState({
planet: planetData,
loading: false
}));
}
apiFetch() 的定义:
export function apiFetch(fetchParam, fullUrl = false, id = false) {
let fetchItem;
let apiUrl;
if (fullUrl) {
apiUrl = fetchParam;
} else {
switch (fetchParam) {
case 'people': {
fetchItem = Constants.apiPeople;
break;
}
case 'planets': {
fetchItem = Constants.apiPlanets;
break;
}
default: {
fetchItem = Constants.apiPlanets;
}
}
apiUrl = Constants.apiBaseUrl + fetchItem;
apiUrl += id ? ('/' + id) : '';
apiUrl += Constants.apiFormat;
}
return fetch(apiUrl, {
method: Constants.fetchMethod,
cache: Constants.apiNoCache
})
.then(response => response.json())
.catch(error => console.error('Error in API:', error));
}
应用程序的流程很好,似乎可以按预期工作,但我无法弄清楚是什么导致了多个 API 请求。
【问题讨论】:
标签: javascript reactjs react-router single-page-application fetch-api