注销时,我希望应用程序重定向到登录页面。当前,当我单击“注销”链接时,它保持在“ / landPage”,但没有内容。
我已经尝试过使用this.props.history.push('/ login')并将组件包装在withRouter中,但这不起作用。我在用链接,但这也不起作用。
接下来我应该尝试什么?
navbar.js
class NavAuth extends Component {
state = {}
onLogout = e => {
e.preventDefault();
window.localStorage.clear();
this.props.logoutUser();
// this.props.history.push('/login');
}
render () {
const { isAuthenticated, user } = this.props.auth;
return (
<Navbar bg="light" expand="sm">
<Navbar.Toggle aria-controls="basic-navbar-nav"/>
<Navbar.Collapse id="basic-navbar-nav">
{isAuthenticated ? (
<Nav className="ml-auto">
<Link to="/chat">Chat</Link>
<Link to="/login" onClick = {this.onLogout}>Logout</Link>
</Nav>
) :(
<Nav className="ml-auto">
<Link to="/registration">Registration</Link>
<Link to="/login">Login</Link>
</Nav>
)}
</Navbar.Collapse>
</Navbar>
)}
}
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(
mapStateToProps,
{logoutUser}
)(NavAuth);
这里是您如何重定向到登录页面的方法。您可以检查isAuthenticated是否为非真值。
import { Redirect } from 'react-router-dom';
class NavAuth extends Component {
state = {}
onLogout = e => {
e.preventDefault();
window.localStorage.clear();
this.props.logoutUser();
// this.props.history.push('/login');
}
render () {
const { isAuthenticated, user } = this.props.auth;
if (!isAuthenticated) return <Redirect to='/login' />
return (
<Navbar bg="light" expand="sm">
<Navbar.Toggle aria-controls="basic-navbar-nav"/>
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="ml-auto">
<Link to="/chat">Chat</Link>
<Link to="/login" onClick = {this.onLogout}>Logout</Link>
</Nav>
) :(
<Nav className="ml-auto">
<Link to="/registration">Registration</Link>
<Link to="/login">Login</Link>
</Nav>
</Navbar.Collapse>
</Navbar>
)}
}
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(
mapStateToProps,
{logoutUser}
)(NavAuth);