错误:无效的钩子调用,React 路由器历史记录
2021-02-19
158
大家好,我是 React 新手,我尝试执行一个函数来注销,但出现此错误。我认为错误与 useHistory 函数有关,因为如果我删除它,一切都会正常。 或者无论如何,有人知道如何以编程方式重定向到另一个页面
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
1个回答
将
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
转换为函数组件(
Logueado
),并从
useLogout
获取
logout
函数。在
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>
Ori Drori
2021-02-19