我必须将登录系统添加到导航栏,但是当我在任何地方登录时,导航栏都不会出现。我该怎么解决?
导航栏正常显示,没有登录系统。
导航栏位于App.js上。
authLinks-仅用于经过身份验证的用户的部分(仪表板和注销按钮)
guestLinks-部分仅用于未经身份验证的用户(在此处登录表单)
我的导航栏+登录:
import React, { Fragment, useState } from "react";
import { Link, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { logout } from "../../actions/auth";
import { login } from "../../actions/auth";
const Navbar = ({ auth: { isAuthenticated, loading }, login, logout }) => {
const [formData, setFormData] = useState({
email: "",
password: ""
});
const { email, password } = formData;
const onChange = e =>
setFormData({ ...formData, [e.target.name]: e.target.value });
const onSubmit = async e => {
e.preventDefault();
login(email, password);
};
if (isAuthenticated) {
return <Redirect to="/dashboard" />;
}
const authLinks = (
<ul>
<li>
<Link to="/dashboard">
<i className="fas fa-user" /> <span className="hide-sm">Dashboard</span>
</Link>
</li>
<li>
<a onClick={logout} href="#!">
<i className="fas fa-sign-out-alt" />{" "}
<span className="hide-sm">Log out</span>
</a>
</li>
</ul>
);
const guestLinks = (
<form
className="form-inline my-2 my-lg-0 navbar-login"
onSubmit={e => onSubmit(e)}
>
<div className="form-group">
<input
className="form-control mr-sm-2"
type="email"
placeholder="Email Address"
name="email"
value={email}
onChange={e => onChange(e)}
/>
</div>
<div className="form-group">
<input
className="form-control mr-sm-2 my-sm-0"
type="password"
placeholder="Password"
name="password"
value={password}
onChange={e => onChange(e)}
/>
</div>
<input type="submit" className="btn btn-primary" value="Login" />
</form>
);
return (
<nav className="navbar navbar-expand-lg navbar-dark bg-dark">
<h1>
<Link className="navbar-brand" to="/">
<i className="fas fa-crown"></i>
<br />
nawdic
</Link>
</h1>
{!loading && (
<Fragment>{isAuthenticated ? authLinks : guestLinks}</Fragment>
)}
</nav>
);
};
Navbar.propTypes = {
logout: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
login: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool
};
const mapStateToProps = state => ({
auth: state.auth,
isAuthenticated: state.auth.isAuthenticated
});
export default connect(mapStateToProps, { login, logout })(Navbar);
答案 0 :(得分:0)
用户登录后,Navbar返回的重定向组件不是导航栏本身
if (isAuthenticated) {
return <Redirect to="/dashboard" />;
}
由于isAuthenticated已传递给Navbar,因此在这种情况下,它不应对重定向负责。 尝试将“重定向”对象移至路由器,这是最佳做法