【问题标题】:Why do I get this error when wanting to use router useNavigate为什么要使用路由器 useNavigate 时出现此错误
【发布时间】:2020-12-16 12:59:29
【问题描述】:

我学习了 React,但不明白如何解决这个简单的错误:

我有一个Codesandbox。

我有这个代码:

/* eslint-disable react/prefer-stateless-function */
import React from 'react';
import { useNavigate } from 'react-router-dom';
import AuthUserContext from './context';

const WithAuthorization = condition => Component => {
    class withAuthorization extends React.Component {
        doStuff = event => {
            const navigate = useNavigate();
            navigate('/', { replace: true });
        };

        render() {
            return (
                <AuthUserContext.Consumer>
                    {authUser => (condition(authUser) ? <Component {...this.props} /> : this.doStuff())}
                </AuthUserContext.Consumer>
            );
        }
    }

    return withAuthorization;
};

export default WithAuthorization;

这条线不起作用是const navigate = useNavigate();的原因,错误是这样的:

错误:无效的挂钩调用。 Hooks 只能在函数组件内部调用

我只想在WithAuthorization 检测到错误路径时离开。

我应该改为使用 Redux 来进行这种处理吗,发送 Redux 操作感觉如此荒谬?

【问题讨论】:

    标签: reactjs react-router-dom higher-order-components


    【解决方案1】:

    这个错误非常自我解释,你需要在函数组件和顶层使用钩子(你不能在函数内部初始化它)所以试试这个:

    const WithAuthorization = condition => Component => {
     return props => {
    
        const navigate = useNavigate();
    
        const doStuff = event => navigate('/', { replace: true });
        
        return (
                <AuthUserContext.Consumer>
                    {authUser => (condition(authUser) ? <Component {...props} /> : doStuff())}
                </AuthUserContext.Consumer>
              );
      } 
    };
    

    【讨论】:

    • dunnu 但我仍然使用你的代码这个“React Hook”useNavigate“在函数“withAuthorization”中被调用,它既不是 React 函数组件也不是自定义 React Hook 函数”
    • 我将useNavigate() 移动到外部函数,然后得到“无法在回调中调用 React Hook "useNavigate"”
    • 这太奇怪了,我读了docs,这应该可以工作
    • 我认为这可能是一个错误,所以我提交了bug report
    • 我收到the same 错误恐怕
    猜你喜欢
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    • 2015-10-16
    相关资源
    最近更新 更多