首页 > 解决方案 > 必须在 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]
}

标签: reactjserror-handlingreact-hooks

解决方案


当我在 useEffect 中使用钩子时,我偶然发现了相同的错误消息。可能与 OP 问题有点无关,但我很确定当你用谷歌搜索错误消息时你会来到这里。

因此,您可以做的是对您的钩子函数使用 ref。

  const { hookFunction } = useMyHook();
  const hookFunctionRef = useRef(hookFunction);

然后在你的 useEffect 中使用 hookFunctionRef.current() 和在你的 useEffect 依赖数组中使用 hookFunctionRef。


推荐阅读