1、封装一个AuthRouter
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
const DATA = {
user: Storage.getStore('user')
}
const AuthRouter = (props) => {
const { component: Component, needLogin } = props;
if (needLogin == false || logined()) {
return (<Route key={props.location.pathname} {...props} component={Component} />);
} else {
return <Redirect exact {...props} from={props.path} to={'/login'} />
}
}
const logined = () => {
return DATA.user != null
}
const Login = (user) => {
DATA.user = user;
Storage.setStore("user", user)
}
const Loginout = () => {
DATA.user = null
Storage.removeStore('user')
}
const getUser = () => {
return DATA.user || {};
}
export { getUser, AuthRouter, Login, Loginout }
2、使用
<HashRouter>
<Suspense fallback={<PageLoading />}>
<Switch>
<AuthRouter exact needLogin={false} path="/login" component={withTracker(Login)} />
<AuthRouter exact path="/work/:type/:cid" component={withTracker(Work)} />
<AuthRouter path="/" component={withTracker(Index)} />
</Switch>
</Suspense>
</HashRouter>