在设置react-router应用程序时,我经常将其设置在回调上以表示授权过滤器 . 这导致我这样的设计:

# before, in my root component
requireAuth() { ... }
noAuth() { ... }
render() {
  return (
    <Router history={this.props.history}>
      <Route path='/' component={App} onEnter={this.requireAuth}>
        <Route path='toys' component={Toys}/>
        ...
      <Route path='/auth' component={Auth} onEnter={this.noAuth}>
        ...
    </Router>
  )
}

我现在正尝试将其移植到nodejs并在服务器中呈现页面 . 突然间,我被要求将所有路线分组成一个常量 . 其次,我丢失了我的根组件和 this. 回调绑定,并且无法在服务器上重新创建相同的体系结构 .

所以我的第一个问题是路线 . 在反应中,我不能返回组件组,而是包含所有其余组件的组件 . 所以,这是我的尝试:

# root component render
# after import routes from './routes'
render() {
  return (
    <Router routes={routes} history={this.props.history}/>
  );
}
# in routes.js
module.exports = (
  <Route> # is this right?
    <Route path='/' component={App} onEnter={this.requireAuth}>
      <Route path='toys' component={Toys}/>
      ...
    <Route path='/auth' component={Auth} onEnter={this.noAuth}>
      ...
  </Route>

所以,这并没有封装主 Route 组件中的所有路由 . 从反应路由器的角度来看,这是正确的吗?我可以使用那种空封装组件吗?

第二个是:我如何在服务器端绑定那些 this. 回调呢?由于我正在按照教程,我的快递路由器看起来像这样:

import routes from './src/components/routes';
...
app.get('*', (req, res) => {
  match(
    { routes, location: req.url },
    (err, redirectLocation, renderProps) => {
....

但它打破了:

onEnter: undefined.requireAuth,
                  ^
TypeError: Cannot read property 'requireAuth' of undefined

哪个是对的,因为路由常量不受任何上下文的约束 .

或者有没有更合适的方法在react-router中执行此操作,并且绑定回调到路由是错误的方法?