javascript - REACT - 未处理的拒绝(错误):无效的挂钩调用
问题描述
所以我正在尝试使用下面的代码来使用 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",
},
我已按照此处的一些答案中的说明将反应包放置到 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
);
}
推荐阅读
- azure-devops - 如何为代理级别故障 Azure 管道发送电子邮件通知
- r - 面对两个包含社会名称的不同向量并在 R 中找到具有完全匹配和准相似匹配的共同元素的最佳方法
- ios - SwiftUI:如何在应用程序组中获取 JSON 的路径?
- aframe - 最新版 A-Frame 中的旋转天空
- react-native - React Native 从设备(iOS 和 Android)读取日历事件
- reactjs - Razorpay Web API 登录提醒
- python - 除非重新启动内核,否则尝试重新运行脚本时出现 bgerror 和冻结
- python - 如何在 Python 中将字母数字列值增加 1 个增量?
- ruby-on-rails - ActionMailer::Base.deliveries.last 不进入 sidekiq 队列
- c++ - 使用 GDI+ 和 Qt Pixmap C++ 时的内存泄漏问题