react-router v4 遍历router后页面空白

我写的静态路由可以正常匹配,页面也会正常显示,但遍历之后点击菜单,路由会变,但页面是空白

这是写的静态路由 可以正常匹配
<Switch>
  <Route path="/index" component={User}/>
  <Route path="/admin" >
    <Switch>
      <Route path="/admin/log" component={Admin}/>
      <Route path="/admin/census" component={Census}/>
      <Route path="/admin/auth" component={SystemAuth}/>

    </Switch>
  </Route>
</Switch>

下面的遍历方法 路由会变,页面空白
const adminRouters = [
    {
      path: '/index',
      component: User,
      title: '用户',
      icon: 'user'
    }, 
    {
      path: '/admin',
      title: '系统',
      icon: 'setting',
      childrens:[
        {
          path: '/admin/log',
          component: Log,
          title: '日志',
        }, 
        {
          path: '/admin/num',
          component: Num,
          title: '统计',
        }
      ]
    } 
]

generateRouter = (adminRouters) => {
    return (
      adminRouters.map(r => {
        if (r.childrens) {
          return (
            <Switch>
              <Route key={r.path} path={r.path} render={routeProps => {
                return (<r.component {...this.props} >
                  {this.generateRouter(r.childrens)}
                </r.component>);
              }}>
              </Route>
            </Switch>
          )
        } else {
          return (
            <Route
              key={r.path}
              path={r.path}
              exact
              render={routeProps => {
                return (<r.component {...routeProps} />);
              }}
            />
          )
        }

      })
    )
  }

render(){
    <Switch>
     {this.generateRouter(adminRouters)} //这是调用方法
     </Switch>
}


阅读 2k
1 个回答
generateRouter = (adminRouters) => {
  return (
    adminRouters.map(r => {
      if (r.childrens) {
        return   <Route key={r.path} path={r.path} render={routeProps => {
                return (<r.component {...routeProps} />);
              }}>
                  <Switch>
                    {this.generateRouter(r.childrens)}
                  </Switch>
                </Route>
     
      } else {
        return (
          <Route
            key={r.path}
        path={r.path}
        exact
        render={routeProps => {
          return (<r.component {...routeProps} />);
        }}
        />
      )
      }

    })
  )
}

是不是应该这样写?

二改:

image.png 跟我这个函数是一个逻辑的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题