首页 > 解决方案 > 在 react-router 5.1 中动态渲染路由

问题描述

我正在尝试将我手动声明的路由组件(在 Route 中)转换为动态渲染,如下所示:

const routes = [
  { path: '/cars', exact: true, component: Cars },
  { path: '/car/:id', component: Car },
  { path: '/login', component: Login },
]

export default function Routing() {
  return (
      <BrowserRouter >
        <Switch>
          {routes.map(({ component, ...rest }, index) => {
            return (
              <Route key={index} {...{ rest }}>
                {React.createElement(component)}
              </Route>
            )
          })}
          <Redirect to="/homes" />
        </Switch>
      </BrowserRouter>
  )
}

我也尝试过以下方法:

{routes.map(({ component: Cmp, ...rest }, index) => {
  return (
    <Route key={index} {...{ rest }}>
      <Cmp />
    </Route>
  )
})}

但以上都没有导致路线。当点击之前有效的链接时,现在什么也没有发生。知道可能出了什么问题吗?

标签: reactjsroutingreact-router

解决方案


你必须做{...rest}而不是{...{ rest }}让它工作。

{...rest}将破坏对象,而{...{rest}}将创建另一个对象,例如{rest: { path: '/login'}}

<Router >
      <Switch>
        {routes.map(({ component, ...rest }, index) => {          
          return (
            <Route {...rest} component={component} />
          )
        })}
      </Switch>
    </Router>

推荐阅读