在使用React JS与Fetch API进行网络请求时,设置超时功能可以确保请求不会无限期地等待响应。Fetch API本身并不直接支持超时设置,但可以通过结合Promise和setTimeout
函数来实现这一功能。
可以通过创建一个包装函数,在该函数中同时启动Fetch请求和一个计时器来实现超时控制。如果计时器先触发,则取消Fetch请求并返回一个超时错误。
以下是一个在React组件中使用Fetch API并设置超时的示例:
import React, { useEffect } from 'react';
function App() {
useEffect(() => {
const fetchDataWithTimeout = (url, options, timeout = 5000) => {
return Promise.race([
fetch(url, options),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('请求超时')), timeout)
)
]);
};
const fetchUrl = 'https://api.example.com/data';
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
};
fetchDataWithTimeout(fetchUrl, requestOptions)
.then(response => {
if (!response.ok) {
throw new Error('网络响应错误');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('发生错误:', error));
}, []);
return <div>正在加载数据...</div>;
}
export default App;
通过上述方法,可以在React应用中有效地管理Fetch API请求的超时问题。
领取专属 10元无门槛券
手把手带您无忧上云