reactjs - 必须在 React 函数组件或自定义 React Hook 函数中调用 React Hooks
问题描述
我正在尝试编写错误处理程序,但出现此错误:无法在回调中调用 React Hook "useHttpErrorHandler"。必须在 React 函数组件或自定义 React Hook 函数中调用 React Hooks 我不知道如何处理这个 errorHandler。
这是 withErrorHandler :
const WithErrorHandler = (WrappedComponent, axios) => {
return props => {
const [error, clearError] = useHttpErrorHandler(axios);
return (
<div>
<ErrorModal show={error} errorModalClosed={clearError}>
{error ? error.message : null}
</ErrorModal>
<WrappedComponent {...props}/>
</div>
)
}
};
export default WithErrorHandler;
这是http-error-handler:
export default httpClient => {
const [error, setError] = useState(null);
const reqInterceptor = httpClient.interceptors.request.use(req => {
setError(null);
return req;
});
const resInterceptor = httpClient.interceptors.response.use(
res => res,
err => {
setError(err);
}
);
useEffect(() => {
return () => {
httpClient.interceptors.request.eject(reqInterceptor);
httpClient.interceptors.response.eject(resInterceptor);
};
}, [reqInterceptor, resInterceptor])
const errorConfirmHandler = () => {
setError(null);
};
return [error, errorConfirmHandler]
}
解决方案
当我在 useEffect 中使用钩子时,我偶然发现了相同的错误消息。可能与 OP 问题有点无关,但我很确定当你用谷歌搜索错误消息时你会来到这里。
因此,您可以做的是对您的钩子函数使用 ref。
const { hookFunction } = useMyHook();
const hookFunctionRef = useRef(hookFunction);
然后在你的 useEffect 中使用 hookFunctionRef.current() 和在你的 useEffect 依赖数组中使用 hookFunctionRef。
推荐阅读
- javascript - (Vue 2)无法在插件中全局注册异步组件以在主项目中使用
- python - 如何使用在归一化输入上训练的模型对看不见的输入进行归一化以进行预测?
- r - 为随机森林树训练数据时出错 - 我该如何解决?
- crash - VM 在通过 VPN 进行 rsync 和 scp 传输期间间歇性崩溃
- node.js - 在函数中执行 Node.JS 终端命令
- python - 如何使用循环访问嵌套列表的元素
- sql - 使用以前的值创建表(迭代过程)
- r - 如何删除使用 break = seq() 时生成的空值
- javascript - 将 Js 转换为 Ts 错误找不到模块
- angular - 在 Angular 单元测试中测试路由方法返回类型错误