我一直在尝试使用基于cookie的登录,如果未设置适当的cookie,则将用户重定向到默认的Login页面。我已经能够重定向到所需的路由,但是我真的不确定在发生上述重定向时在哪里注册要加载什么组件。有人可以帮我吗?请在下面找到我的代码:
import React, { Component } from "react";
import Cookies from 'js-cookie';
import {Redirect} from "react-router-dom";
import {LoginPage} from './LoginPage';
import {InputTable} from './InputTable';
export class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: false
};
}
checkCookieBasedLogin(){
let session_cookie = Cookies.get("groclist_session_token");
if (session_cookie === null || session_cookie === undefined || session_cookie === "") {
this.setState({
isLoggedIn: false
});
} else {
this.setState({
isLoggedIn: true
});
}
}
componentDidMount(){
this.checkCookieBasedLogin();
}
render() {
if (this.state.isLoggedIn) {
return <Redirect push to="/input"></Redirect>
} else{
return <Redirect push to="/login"></Redirect>
}
}
}
在这里,LoginPage
和InputTable
是功能齐全的反应组件,已经过单独测试。
您必须使用路由器模块。
import { Router, Route, Redirect } from 'react-router';
const App: () => {
if (this.state.isLoggedIn) {
return <Redirect push to="/input" />
} else {
return <Redirect push to="/login" />
}
<Router>
<Route path="/input" component={Input} />
<Route path="/login component={Login} />
</Router>
}