[英]Error: Invalid hook call, React router history
大家好,我是反應初學者,我嘗試執行 function 注銷,但我收到此錯誤。 我認為該錯誤與 useHistory function 有關,因為如果我刪除它,一切正常。 或者無論如何,有人知道如何以編程方式重定向到另一個頁面
Error: Invalid hook call. Hooks can only be called inside of the body of a function component
這是我的代碼。
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import token from '../services/token'
import api from '../services/api'
import { useHistory } from 'react-router-dom';
const noLogueado = <React.Fragment>
<li className="nav-item">
<Link className="nav-link" to="/login">Login</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/register">Registrarse</Link>
</li>
</React.Fragment>;
const logueado = <li className="nav-item dropdown">
<a className="nav-link dropdown-toggle" href="#" role="button" id="dropdownPerfil" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
NAME USUARIO
</a>
<div className="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownPerfil">
<a className="dropdown-item" href="#">Mi Perfil</a>
<a className="dropdown-item" href="#" onClick={() => Logout()}>Cerrar sesión</a>
</div>
</li>;
const Logout = () => {
let history = useHistory();
api.post("logout", "").then(
(data) => {
// token.remove();
history.push('/login');
},
(error) => {
// token.remove();
history.push('/login');
}
);
}
export class NavBar extends Component {
render() {
return (
<nav className="navbar navbar-expand navbar-dark bg-dark">
<Link className="navbar-brand" to="/">
Home</Link>
<div className="collapse navbar-collapse">
<ul className="navbar-nav ml-auto">
{
token.isValid() ? logueado : noLogueado
}
</ul>
</div>
</nav>
)
}
}
export default NavBar
將Logout
重命名為useLogout
(因為它是一個自定義鈎子):
const useLogout = () => {
let history = useHistory();
return useCallback(() => api.post("logout", "").then(
(data) => {
// token.remove();
history.push('/login');
},
(error) => {
// token.remove();
history.push('/login');
}
), [history]);
}
將logueado
轉換為 function 組件( Logueado
),並從useLogout
獲取logout
function 。 調用 onClick 中的onClick
。
const Logueado = () => {
cosnt logout = useLogout()
return (
<li className="nav-item dropdown">
<a className="nav-link dropdown-toggle" href="#" role="button" id="dropdownPerfil" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
NAME USUARIO
</a>
<div className="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownPerfil">
<a className="dropdown-item" href="#">Mi Perfil</a>
<a className="dropdown-item" href="#" onClick={logout}>Cerrar sesión</a>
</div>
</li>;
)
}
由於Logueado
現在是一個組件,因此在NavBar
渲染方法中渲染它:
<ul className="navbar-nav ml-auto">
{
token.isValid() ? <Logueado /> : noLogueado
}
</ul>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.