I want to use different routing based on some partial state, so I came up with the following:
in my entry file:
import routes from './routes.js'
ReactDOM.render(
<IntlProvider locale={locale} messages={messages[locale]}>
<Provider store={store} key='provider'>
<div>
<Router history={history} routes={routes(store)} />
</div>
</Provider>
</IntlProvider>,
document.getElementById('root')
)
routes.js:
export default (store) => (
let isAuthenticated = store.getState().auth.isAuthenticated
if(isAuthenticated) {
return (
<Route component={Tool}>
<IndexRoute component={Dashboard} />
<Route path="products" component={Products} />
</Route>
)
} else {
return (
<Route>
<Route component={Site}>
<IndexRoute component={Home} />
<Route path="pricing" component={Pricing} />
</Route>
<Route component={Portal}>
<Route path="login" component={Login} />
<Route path="register" component={Register} />
</Route>
</Route>
)
}
)
This works, but only if I actually refresh the page. It will however not transition from Home component to Dashboard component if I just login without refreshing the browser page, so I suspect the routes object is build only once at the beginning and builds up on the current state, but will not change if the state changes mid execution.
I also found https://github.com/ReactTraining/react-router/blob/master/docs/guides/DynamicRouting.md this concerning dynamic routes but as I tried it it doesn't seem to do what I hoped or expected it to do.
You can use the onEnter
method on the route level
<Route name="example" path="/example" component={Example} onEnter={functionToCheckAuthorization()} />
With a function to check authorisation eg
function functionToCheckAuthorization(nextState, replace) {
if (!auth.loggedIn()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
Please see reference: https://github.com/ReactTraining/react-router/blob/master/examples/auth-flow/app.js
Also see reference: https://github.com/ReactTraining/react-router/issues/243 to explain the intentions behind using auth-flow as an example
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.