如何在React Router dom v4上的嵌套路由中获取参数?

时间:2019-02-05 19:56:28

标签: javascript reactjs react-router-dom

这就是我定义路由器的方式。

   <Switch>
     {routes.map((route, index) => (
        <Route
          {...this.props}
          path={`/${route}`}
          key={index}
          component={props => (
            <Layout
              {...props}
            />
          )}
        />
      ))}
      <Route component={() => <p>Not Found</p>} />
    <Switch>

我从routes数组中生成了一些路由,对于任何不匹配的route,它都会到达未找到的路由。

Layout组件中,我进一步创建了类似这样的其他路由-

   <div className={"Actionbar"}>          
      <Route
        path={`${props.match.url}/:item`}
        component={() => <EditCategory {...props} />}
      />            
    </div>

当我导航到嵌套路线时,假设/edibles/icecream,我应该能够看到icecream是属性item的参数值,对吗?我看不到它,我似乎也无法弄清楚如何在此嵌套路由用例中获取id参数值。我的param对象现在看起来是空的。

1 个答案:

答案 0 :(得分:0)

找到了解决方案。 props需要与route一起传递。像这样-

<div className={"Actionbar"}>          
  <Route
    path={`${props.match.url}/:item`}
    component={(props) => <EditCategory {...props} />}
  />            
</div>

缺少此选项不会传递match