使用react-router0-config時的簡易守衛

vapidness_Q發表於2020-12-27

import React from ‘react’
import { renderRoutes } from ‘react-router-config’
import { withRouter, Link } from ‘react-router-dom’

import { Home, Login, Forms, List, Main } from ‘./components’

const Root = ({ route }) => (

{renderRoutes(route.routes)}
);

class Router extends React.Component {
componentWillMount() {
const { location } = this.props
if(!sessionStorage.getItem(‘token’)&&location.pathname!’/login’){
this.props.history.push(’/login’)
}
}
componentWillReceiveProps(nextProps) {
if(!sessionStorage.getItem(‘token’)&&nextProps.location.pathname!
’/login’){
this.props.history.push(’/login’)
}
}
routes = [
{
component: Root,
routes: [
{
path: “/login”,
component: Login,
},
{
path: “/home”,
component: Home,
routes: [
{
path: “/home/edits”,
component: Forms,
},
{
path: “/home/forms”,
component: Forms,
},
{
path: “/home/list”,
component: List,
},
]
},
{
path: “/”,
component: Main,
}
]
}
];
render() {
return (
<>


<span style={{ display: ‘inline-block’, margin: ‘0 5px’ }}>login
<span style={{ display: ‘inline-block’, margin: ‘0 5px’ }}>home
<span style={{ display: ‘inline-block’, margin: ‘0 5px’ }}>main

{renderRoutes(this.routes)}
</>
)
}
}
export default withRouter(Router)

相關文章