无法匹配/ recipes /:id / ingredients等动态路由

时间:2017-02-28 13:51:51

标签: node.js reactjs react-router

我正在使用npm包react-router-dom@4.0.0-beta.6作为我的反应应用程序。

我可以匹配以下路线:

  • /trends
  • /news
  • /recipes

但我无法匹配以下路线:

  • /recipes/:id/ingredients/recipes/1234/ingredients

如果我从/recipes/1234切换到/recipes/1234/ingredients我只匹配路线/recipes/:id,但不匹配/recipes/:id/ingredients

该应用程序如下所示:

const factory = (name, path) => {
  return (props) => {
    const { children, match, routes } = props;
    const { params } = match;

    // convert the child routes from /recipes/:id/ingredients to /recipes/1234/ingredients
    const others = routes.map(x => pathToRegexp.compile(x.path)(params));

    return (
      <div>
        <h3>{name}</h3>

        <ul>
          {others.map(x =>
            <Link key={x} to={x}>{x}</Link>
          )}
        </ul>

        {children}
      </div>
    );
  };
};

const rootPattern = '/recipes/:id';

const routes = [
  {
    path: rootPattern,
    component: factory('Root', rootPattern),
    routes: [
      {
        path: `${rootPattern}/ingredients`,
        component: factory('Ingredients', `${rootPattern}/ingredients`),
      },
      {
        path: `${rootPattern}/steps`,
        component: factory('Steps', `${rootPattern}/steps`),
      },
    ],
  },
];

// wrap <Route> and use this everywhere instead, then when
// sub routes are added to any route it'll work
const RouteWithSubRoutes = (route) => (
  <Route path={route.path} render={props => (
    // pass the sub-routes down to keep nesting
    <route.component {...props} routes={route.routes}/>
  )}/>
);

const RouteConfigExample = () => (
  <Router>
    <div>
      <ul>
        <li><Link to="/recipes/1234">Sandwiches</Link></li>
      </ul>

      {routes.map((route, i) => (
        <RouteWithSubRoutes key={i} {...route}/>
      ))}
    </div>
  </Router>
);

公平地说,我不明白为什么我的应用程序与动态路线不匹配。

您可以在https://github.com/jbrieske/react-router-config找到完整的示例。

0 个答案:

没有答案