[英]How to make a react class component retain its state after login and change available routes based on the state currently available in the component?
I was working on a simple react app.我正在开发一个简单的反应应用程序。 What I aim to do is that i want to make only the user/login and /user/register URLS accessible to the user until the user logs in. So on authentication i am changing the Routes.
我的目标是,在用户登录之前,我只想让用户访问用户/登录和/用户/注册 URL。因此,在身份验证时,我正在更改路由。 Currently i am being routed to /projects page(the new routes are populated in the app) but on refreshing i am being redirected to /user/login.
目前我被路由到 /projects 页面(新路由填充在应用程序中)但是在刷新时我被重定向到 /user/login。 Is there a way where I can do this without saving anything in localstorage?
有没有一种方法可以做到这一点而不在本地存储中保存任何内容? Can anyone help me resolve this?
谁能帮我解决这个问题?
import './App.css';
import LoginForm from './components/LoginForm/LoginForm'
import RegistrationForm from './components/RegistarationForm/RegistarationForm';
import Project from './components/Project/Project';
import {
BrowserRouter as Router,
Switch,
Route,
Redirect,
} from "react-router-dom";
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state={
isUserAuthenticated: false
};
console.log('APP constructor');
}
// componentDidUpdate(prevProps) {
// console.log('update');
// }
authenticateUser=()=>{
this.setState({
isUserAuthenticated: true
});
}
render(){
var routes;
if(!this.state.isUserAuthenticated){
routes=<React.Fragment>
<Route exact path="/user/login" ><LoginForm authenticateUser={this.authenticateUser}/></Route>
<Route exact path="/user/register"><RegistrationForm /></Route>
<Route
render={() => <Redirect to={{pathname: "/user/login"}}/>}
/>
</React.Fragment>;
}else{
routes=<React.Fragment>
<Route exact path="/projects" ><Project /></Route>
<Route
render={() => <Redirect to={{pathname: "/projects"}}/>}
/>
</React.Fragment>;
}
return (
<Router>
<Switch>
{routes}
</Switch>
</Router>
);
}
}
export default App;
I am Brazilian and therefore I speak Portuguese, but I will use the translator to try to help you.我是巴西人,因此我会说葡萄牙语,但我会使用翻译来帮助您。
I didn't really understand what's going on, but I still think you can do the following:我真的不明白发生了什么,但我仍然认为您可以执行以下操作:
render() {
return (
<Router>
<Switch>
{!this.state.isUserAuthenticated ? (
<React.Fragment>
<Route exact path="/user/login">
<LoginForm authenticateUser={this.authenticateUser} />
</Route>
<Route exact path="/user/register">
<RegistrationForm />
</Route>
<Route
render={() => <Redirect to={{ pathname: "/user/login" }} />}
/>
</React.Fragment>
) : (
<React.Fragment>
<Route exact path="/projects">
<Project />
</Route>
<Route
render={() => <Redirect to={{ pathname: "/projects" }} />}
/>
</React.Fragment>
)}
</Switch>
</Router>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.