【发布时间】: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