[英]Dynamic React-Router routes
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: route.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.
但是,如果我只是登录而未刷新浏览器页面,它将不会从Home组件转换为Dashboard组件,因此我怀疑route对象在开始时仅构建了一次并建立在当前状态上,但是如果状态改变了,则不会改变中期执行。
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. 我还发现https://github.com/ReactTraining/react-router/blob/master/docs/guides/DynamicRouting.md与动态路线有关,但是在我尝试过时,它似乎并没有实现我希望或期望的功能去做。
You can use the onEnter
method on the route level 您可以在路由级别使用
onEnter
方法
<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 请参阅参考资料: 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 另请参阅参考资料: https : //github.com/ReactTraining/react-router/issues/243,以解释使用auth-flow作为示例的意图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.