成功登录后,它会将我重定向到主页,但是当我进入浏览器并打开http://localhost:3000/MainPage时,它会显示我主页(实际上,它必须将我扔到登录页面,因为我没有登录)。就我而言,我无需使用url即可访问主页。为了将未登录的用户重定向到“登录”页面,该怎么办?
在我的LogIn.js中,我将登录状态设置为false
App.js
class App extends Component {
render() {
return (
<BrowserRouter>
<Switch>
<Route exact path="/" component={ LogIn }></Route>
<Route path='/' component={ MainPage }></Route>
</Switch>
</BrowserRouter>
);
}
}
export default App;
LogIn.js
const userIdRegex = RegExp(
/^[uU]*1+[0-9]*$/
);
class LogIn extends Component {
constructor(props) {
super(props);
this.state = {
userId: null,
password: null,
fullName: undefined,
responseError: false,
loggedIn: false,
formErrors: {
userId: "",
password: ""
}
};
}
handleSubmit = e => {
e.preventDefault();
axios.post('url', {
userId:
e.target.elements.userId.value,
password: e.target.elements.password.value })
.then((response) => {
console.log(response);
this.setState({ fullName: response.data.fullName, loggedIn: true });
console.log(this.state.fullName);
console.log(this.state.loggedIn);
}).catch((error) => {
console.log(error);
this.setState({ responseError: true });
});
};
handleChange = e => {
e.preventDefault();
const { name, value } = e.target;
let formErrors = { ...this.state.formErrors };
switch (name) {
case "userId":
formErrors.userId = userIdRegex.test(value)
? ""
: "Invalid user ID";
break;
case "password":
formErrors.password =
value.length < 8 ? "Invalid password" : "";
break;
default:
break;
}
this.setState({ formErrors, [name]: value }, () =>
console.log(this.state));
};
render() {
const { formErrors } = this.state;
const responseError = this.state.responseError;
// const loggedIn = this.state.loggedIn;
// const { from } = this.props.location.state || '/';
if (this.state.loggedIn == true) {
return <Redirect to="./MainPage" />;
}
return (
<div className="wrapper">
<div className="form-wrapper">
<img src={Logo} className="App-logo" alt="Logo" />
<p>To Log In enter your user ID and password.</p>
<form onSubmit={this.handleSubmit} noValidate>
<div className="userId">
<input
autoFocus
className={formErrors.userId.length > 0 ? "error" : null}
placeholder="User ID"
type="text"
name="userId"
noValidate
defaultValue="u"
onChange={this.handleChange}
/>
{formErrors.userId.length > 0 && (
<span className="errorMessage">{formErrors.userId}</span>
)}
</div>
<div className="password">
<input
className={formErrors.password.length > 0 ? "error" : null}
placeholder="Password"
type="password"
name="password"
noValidate
onChange={this.handleChange}
/>
{formErrors.password.length > 0 && (
<span className="errorMessage">{formErrors.password}</span>
)}
</div>
<div className="createAccount">
<button type="submit" disabled={!this.state.userId} disabled=
{!this.state.password}>Log in</button>
</div>
</form>
{ responseError==true && (
<span className="response-error errorMessage">Please enter valid
user values</span>
) }
</div>
</div>
)}
}
export default LogIn;
MainPage.js
class MainPage extends Component {
state = {
loggedIn: false
}
render(){
if (this.state.loggedIn) {
return <Redirect to="/" />;
}
console.log(this.state);
return(
<div>
<p>Welcome</p>
</div>
);
}
}
export default MainPage;
答案 0 :(得分:0)
似乎您的main.js组件具有相反的功能。在if语句中,您需要检查!this.state.loggedIn,然后使用
<Redirect to=‘’./LoginPage”/>
就像您在登录组件中所做的一样。 我在这里看到的问题(也许是我遗漏了一些东西)是,即使从登录后重定向后,MainPage的state.loggedIn也将设置为false。 您可以使用
将loginIn变量从LoginPage传递到MainPage。<Redirect to={{pathname: “./MainPage”, state: {loggedIn: this.state.loggedIn}}} \>
然后,您可以访问用户是否实际上已在MainPage组件中使用this.props.location.state.loggedIn登录。
您当前在主页中拥有它的方式,因为state.loggedIn默认为false,并且您可以通过条件检查loginIn是否为true,所以永远不会触发它。
答案 1 :(得分:0)
一个好的方法是创建一个自定义Route来处理用户是否为auth,如果用户不是auth,则重定向到Login。
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route { ...rest }
render={props => {
if ( isLogged() ) {
return <Component {...props} />;
} else {
return <Redirect to={{pathname:'/login'}} />;
}
}}
/>
);