【问题标题】:REACT - Unhandled Rejection (Error): Invalid hook call反应 - 未处理的拒绝(错误):无效的挂钩调用
【发布时间】:2021-07-22 11:51:40
【问题描述】:

所以我尝试使用下面的代码来使用 react-router-dom 包的 useHistory。

function AdminLogin() {

    const LoginAct = async () => {    
        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ password: hash })
        };
        await fetch('/post/admin/login', requestOptions).then(HandleResponse);
    }
    
    const HandleResponse = async (response) => {
        return response.text()
            .then(text => {
            if (response.ok) {
                var data = text && JSON.parse(text);
                data = data[0];
                if (data != null) {
                    LoginRoute();
                }
            }
        })
    }

    function LoginRoute() {
        const history = useHistory(); 
        history.push('/student/app');
    }

    return (
            // View here including button that calls LoginAct when clicked
        );

}

export default AdminLogin;

但是我正面临来自const history = useHistory(); 的这个错误:

我已尝试使用错误消息中显示的 URL 中的说明进行调试。没有运气! 我的 react 和 React DOM 版本:

  "peerDependencies": {
    "react": "^17.0.2"
  },
  "dependencies": {
    "react-dom": "^17.0.2",
  },

我已按照一些答案here 中的说明将react 包放置到peerDependecies! 我还测试了从上面的 github 问题中找到的其他解决方案。清除我的 npm 缓存并更新我所有的包

除了我违反 Hooks 规则之外,我不知道是什么导致了这个问题,在这种情况下,我不知道我是如何破坏它们的。 (我也安装了 eslint 来执行 Hooks 规则,但可能是我设置错了)

【问题讨论】:

  • const history = useHistory();这应该在 AdminLogin 函数的开头调用。

标签: javascript reactjs


【解决方案1】:

钩子需要在组件的顶层调用。也没有理由将单行抽象为额外的回调,只需在异步处理程序中执行 PUSH。

function AdminLogin() {
    const history = useHistory(); // <-- here

    const LoginAct = async () => {    
        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ password: hash })
        };
        await fetch('/post/admin/login', requestOptions).then(HandleResponse);
    }
    
    const HandleResponse = async (response) => {
        return response.text()
            .then(text => {
            if (response.ok) {
                var data = text && JSON.parse(text);
                data = data[0];
                if (data != null) {
                    history.push('/student/app'); // <-- called here
                }
            }
        })
    }

    return (
            // View here including button that calls LoginAct when clicked
    );
}

【讨论】:

    猜你喜欢
    • 2021-11-23
    • 1970-01-01
    • 2018-06-21
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2020-09-21
    相关资源
    最近更新 更多