![](/img/trans.png)
[英][Unhandled promise rejection: Error: Invalid hook call. Hooks can only be called inside of the body of a function component
[英]REACT - Unhandled Rejection (Error): Invalid hook call
所以我正在尝试使用下面的代码来使用 react-router-dom package 的 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",
},
我已按照此处的一些答案中的说明将反应 package 放置到 peerDependecies 。 我还测试了从上面的 github 问题中找到的其他解决方案,例如。 清除我的 npm 缓存并更新我所有的包
除了我违反 Hooks 规则之外,我不知道是什么导致了这个问题,在这种情况下,我不知道我是如何破坏它们的。 (我也安装了 eslint 来执行 Hooks 规则,但我可能设置错了)
钩子需要在组件的顶层调用。 也没有理由将单行抽象为额外的回调,只需在异步处理程序中执行 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
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.