【问题标题】:Dynamically render routes in react-router 5.1在 react-router 5.1 中动态渲染路由
【发布时间】:2020-02-13 13:08:13
【问题描述】:

我正在尝试将我手动声明的路由组件(在 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>
  )
})}

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

【问题讨论】:

    标签: reactjs routing react-router


    【解决方案1】:

    您必须使用{...rest} 而不是{...{ rest }} 才能使其工作。

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

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

    【讨论】:

      猜你喜欢
      • 2018-01-06
      • 1970-01-01
      • 2018-10-18
      • 2017-06-07
      • 2017-11-15
      • 2019-03-13
      相关资源
      最近更新 更多