如何在通用健壮的UI Fetch实现中集成react-router的navigate?
可复用Fetch实现的异常处理修复
问题现象
你编写的myFetch函数在请求出错时,虽然会跳转到错误页面,但调用方的then方法仍会执行,且拿到的data为无效值(undefined)。
问题原因
当myFetch的catch块捕获到异常后,没有重新抛出错误。由于这是一个async函数,默认会返回undefined,导致调用方的then会接收到undefined并执行后续逻辑。
修复方案
在catch块中完成导航跳转后,重新抛出错误,这样调用方可以通过.catch捕获异常,或者直接忽略(如果不需要额外处理),避免无效的then执行。同时优化代码细节,让逻辑更简洁:
export const myFetch = async (requestUrl, navigate = undefined, { method = 'GET', body } = {}) => { const config = { method, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }; if (method === 'POST' && body) { config.body = JSON.stringify(body); } try { const response = await fetch(requestUrl, config); if (!response.ok) { throw new Error(`${response.status}: ${response.statusText}`); } return await response.json(); } catch (error) { console.error(`ERROR: ${error.message}`); navigate && navigate('/error', { state: { errorMessage: error.message } }); // 重新抛出错误,阻止后续then执行并传递错误信息 throw error; } };
调用示例优化
调用时可以通过.catch处理异常(或结合async/await用try/catch),避免无效逻辑执行:
import { useNavigate } from 'react-router-dom'; const MyComponent = () => { const navigate = useNavigate(); useEffect(() => { myFetch('/some/bad/url', navigate) .then(data => { // 仅在请求成功时执行数据处理 console.log(data); }) .catch(err => { // 可选:添加组件内的额外错误处理逻辑 }); }, []); };
或者用async/await写法更直观:
import { useNavigate } from 'react-router-dom'; const MyComponent = () => { const navigate = useNavigate(); useEffect(() => { const fetchData = async () => { try { const data = await myFetch('/some/bad/url', navigate); // 请求成功时处理数据 console.log(data); } catch (err) { // 可选的额外错误处理 } }; fetchData(); }, []); };
内容的提问来源于stack exchange,提问作者SkyWalker
相关产品推荐
相关产品推荐

