你可以有一个withFetch
HOC 来注入你修改后的 fetch 函数或一个简单的自定义钩子。
1. HOC 实现
// UNTESTED
function withFetch(Component) {
return function(props) {
const [error, setError] = React.useState(false);
// modified fetch
const doFetch = React.useCallback((url, options) => {
try {
fetch(url, options)
// proceed if successful
} catch(error) {
setError(true);
// TODO: add other states to store error message
}
}, [params])
// run effect every time there's fetch error
React.useEffect(() => {
if (error) {
// TODO: do something
}
}, [error]);
return <Component fetch={doFetch} {...props} />
}
}
const EnhancedComponent = withFetch(MyComponent)
return <EnhancedComponent accessToken="some token" />
2.自定义挂钩
function hasFetchError(url, options) {
const [error, setError] = React.useState(false);
React.useEffect(() => {
async function doFetch() {
try {
await fetch(url, options)
// do something with response
} catch(error) {
setError(true);
}
}
doFetch();
}, [url, options])
return error;
}
// Usage:
function MyComponent(props) {
const error = hasFetchError(props.url, props.options);
if (error) {
// do something
}
}