所以我正在尝试使用以下代码使用 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 包放置到 peerDependencies! 我还测试了从上面的 github 问题中找到的其他解决方案,例如。清除我的 npm 缓存并更新我的所有包
除了我违反 Hooks 规则之外,我不知道是什么导致了这个问题,在这种情况下我不知道我是如何打破它们的。 (我也安装了 eslint 来执行 Hooks 规则,但可能是我设置错了)
答案 0 :(得分:0)
钩子需要在组件的顶层调用。也没有理由将单行抽象为额外的回调,只需在异步处理程序中执行 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
);
}