Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

javascript - How to get current route in react-router 2.0.0-rc5

I have a router like below:

<Router history={hashHistory}>
    <Route path="/" component={App}>
        <IndexRoute component={Index}/>
        <Route path="login" component={Login}/>
    </Route>
</Router>

Here's what I want to achieve :

  1. Redirect user to /login if not logged in
  2. If user tried to access /login when they are already logged in, redirect them to root /

so now I'm trying to check user's state in App's componentDidMount, then do something like:

if (!user.isLoggedIn) {
    this.context.router.push('login')
} else if(currentRoute == 'login') {
    this.context.router.push('/')
}

The problem here is I can't find the API to get current route.

I found this closed issue suggested using Router.ActiveState mixin and route handlers, but it looks like these two solutions are now deprecated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After reading some more document, I found the solution:

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md

I just need to access the injected property location of the instance of the component like:

var currentLocation = this.props.location.pathname

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...