![](/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.