【问题标题】:Passing parameters to dynamically generated react routes将参数传递给动态生成的反应路线
【发布时间】:2026-02-17 02:30:01
【问题描述】:

我正在使用react-router-dom 并从这样的数组动态生成我的路线

路线数据

const routes = [
  {
    path: '/',
    exact: true,
    component: () => <MyComponent />
  }
}

路线生成

{routes.map((route, index) => {
  return <Route
    key={index}
    path={route.path}
    exact={route.exact}
    component={route.component}
  />
})}

渲染道具 我发现了我可以定义的 render() 道具,但即便如此,我该怎么做,因为组件在变量中

const props = this.props;
{routes.map((route, index) => {
  return <Route
    key={index}
    path={route.path}
    exact={route.exact}
    render={(props) => <??? {...props} />
  />
})}

如何在路由生成过程中传递 this.props?

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom


    【解决方案1】:

    您可以更改您的数组以仅包含组件而不是呈现组件的新功能组件,您将获得发送给它的道具:

    const routes = [
      {
        path: '/',
        exact: true,
        component: MyComponent
      }
    }
    

    您可以使用任何大写的变量作为组件,因此如果您愿意,也可以这样做:

    {routes.map((route, index) => {
      const Component = route.component;
    
      return <Route
        key={index}
        path={route.path}
        exact={route.exact}
        render={(props) => <Component {...props} />
      />
    })}
    

    【讨论】:

    • 啊谢谢你,太棒了!您将如何处理重定向案例?例如,我在实际实现中的数组有一些路由对象,其中组件是重定向,例如{ path: '/', exact: true, component: &lt;Redirect to='/other/route' /&gt; }, 我在想可能会添加一个额外的字段重定向:'/other/route' 到我的路由对象,然后在我的循环中执行如果定义了一个条件?
    • @Newton 不客气!为此,第二种方法可能是最好的。 { component: MyComponent } 用于常规组件,{ component: () =&gt; &lt;Redirect to='/other/route' /&gt; } 用于您的重定向应该可以工作。添加一个单独的字段redirect: '/other/route' 也应该很好用。
    • 一切就绪,一切正常,再次感谢 Tholle,非常感谢!