路由逻辑和React Router v4的问题

时间:2017-06-23 18:33:15

标签: reactjs react-router

我正在构建一个小应用程序,我在前端使用了ReactJs,在后端使用了jwt和passport。我使用react路由器v4,我已经配置了这样的应用程序路由。

import React,{Component} from 'react';
import Login from './login/login';
import Signup from './signup/signup';
import Account from './account/account';
import Navigation from './navigation/navigation';
import Newsfeeds from './newsfeed/feedcontainer';
import Test from './test';
import NotMatch from './nomatch/Notmatch';
import injectTapEventPlugin from 'react-tap-event-plugin';
import createBrowserHistory from 'history/createBrowserHistory';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';

const history = createBrowserHistory({});
injectTapEventPlugin();

let hasToken = () => {
  const token = localStorage.getItem('jwtToken');
  return (token == undefined);
}

class App extends Component{

  render(){
    return(
      <MuiThemeProvider>
       <Router history={history}>
         <Switch>
           <Route path="/login" exact component={Login}/>
           <Route path="/signup" exact component={Signup}/>
           <Route path="/test" exact component={Test}/>
            <Navigation>
             <Route path="/account" exact render={() => (hasToken() ? (<Account />) : (<Redirect to="/login"/>))}/>
             <Route path="/home"  exact render={() => (hasToken() ? (<Newsfeeds />) : (<Redirect to="/login"/>))}/>
           </Navigation>
           <Route component={NotMatch}/>
         </Switch>
       </Router>
     </MuiThemeProvider>
    );
  }

}

export default App;

注销代码

<Link to="/login"><MenuItem primaryText="Logout" onTouchTap={e=>{localStorage.clear();}}></MenuItem></Link>

当我尝试注销(清除我的本地存储并重定向到登录路由)时,它会陷入循环并且应用程序中断。怎么避免这个? 如何限制/验证路由。当用户尝试移至/login/signup路由时,已登录时切换到主页。

0 个答案:

没有答案