问题
I have seen multiple threads that suggest the use of Routes on redux, but in general, the examples contain a public Main Page with the options to Log in, Logout, Access to Dashboard, etc. What I'm looking for is to allow the user to access the app if the token is still valid, otherwise, it should redirect to the Login page, which is not part of the main layout of the app. Let me show some code:
function checkAuth() {
const token = localStorage.getItem('token');
if (!token) {
return false;
}
try {
let payload = decode(token);
if (payload.exp < new Date().getTime() / 1000) {
return false;
}
} catch (e) {
return false;
}
return true;
}
class Main extends Component {
constructor(props) {
super(props);
this.output = this.output.bind(this)
this.state = { loggedin: false }
}
output(evt) {
this.setState({loggedin: evt})
}
Content({output, loggedin})
{
if (checkAuth())
return(<Layout/>);
if (!loggedin)
return(<Login func={output}/>);
else
return(<Layout/>);
}
render() {
return (
<this.Content output={this.output} loggedin={this.state.loggedin}/>
)
};
}
First, I made validation of the token; if it is still valid, the function " Content" will return the Dashboard, otherwise, it will return the Login Page. Then, I send a function "output" to the child component "Login", so the Login page is able to change the state of the flag "loggedin", the change of this state will render the dashboard.
My App component:
class App extends Component {
render() {
return (
<div className="App">
<Router>
<Route path="/" component={Main} />
</Router>
</div>
)
};
}
It works by now as expected, but I have the feeling the code logic can be improved. It would be helpful for some opinions about it, I'm a React beginner. I have published the code on Github: Full Code
回答1:
You could create a component called "ProtectedRoute" where inside it does the token validation logic and in case there's no token, it redirects you to the login page
// Packages
import React, { Fragment } from 'react';
import { Route, Redirect } from 'react-router-dom';
const ProtectedRoute = ({ component: Component, ...rest }) => {
const checkValidToken = () => {
const token = localStorage.getItem('token');
// Validation logic...
}
return (
<Fragment>
{checkValidToken()
? <Route {...rest} render={props => <Component {...rest} {...props} />} />
: <Redirect to="/auth?mode=login" />
}
</Fragment>
);
}
export default ProtectedRoute
and then use it as follow
class App extends Component {
render() {
return (
<div className="App">
<Router>
<ProtectedRoute path="/" component={Main} />
</Router>
</div>
)
};
}
来源:https://stackoverflow.com/questions/64628792/redirect-to-login-page-when-token-is-invalid-on-react