反应:路由不在循环内工作

时间:2018-10-14 02:05:07

标签: javascript reactjs react-router-dom

为什么这不起作用?

<Provider store={ store }>
   <BrowserRouter>
       <Switch>
          {routes && routes.map(
              (config, i) => <PrivateRoute key={ `route-render-${ i }` } config={ config } />
          )}
       </Switch>
   </BrowserRouter>
</Provider>

但是,如果我将PrivateRoute更改为Route,则组件的内容将正常运行。

这是我的PrivateRoute.js

import React, { Component } from 'react'
import { Route } from 'react-router-dom'

class PrivateRoute extends Component {
    render() {
        const { config: { access, roles, ...rest } } = this.props

        return (
            <Route { ...rest } />
        )
    }
}

export default PrivateRoute

这是routes的样子

import * as shared from '../modules/shared/pages'

export const routes = [
    {
        path: '/',
        roles: [],
        access: [],
        exact: true,
        name: 'Login',
        component: shared.Login
    },
    {
        name: 'PageNotFound',
        component: shared.PageNotFound
    }
]

1 个答案:

答案 0 :(得分:1)

PrivateRoute 需要有 path, exact, component, render props,所有的普通路由 props。

所以你可以做的是传递这些道具以及像

这样的附加配置
<PrivateRoute path={config.path} component={config.component} config={config} />