反应子嵌套路线

时间:2020-06-04 08:45:43

标签: javascript reactjs react-router

我正在尝试在Reactjs中实现子/嵌套路由,下面是我发现的两种嵌套子路由的方法,但是父路由可以正常工作,而父组件的子路由却不能。

以下是其工作方式:

/ => Home Component
/login => Login Component
/register => Register Componet

/product/ => ProductListing Component 
/product/2 => ProductDetails Component [Expected but does not work]
/product/2/edit => ProductEdit Component [Expected but does not work]

方法1

以下是我的主要路线文件:

export default function MainRouter() {
  return (
    <Router>
      <Route exact path="/" component={Home} />
      <Route exact path="/login" component={Login} />
      <Route exact path="/register" component={Register} />
      <Route exact path="/product" component={ProductRouter} />
    </Router>
  );
}

产品的子路线,如下ProductRouter.js文件中所示

export default function ProductRouter(props) {
  console.log(props);

  return (
    <Switch>
      <Route
        exact
        path={`${props.match.path}/:productId`}
        component={ProductDetails}
      />
      <Route
        exact
        path={`${props.match.path}/:productId/edit`}
        component={ProductEdit}
      />
      <Route exact path={`${props.match.path}`} component={ProductListing} />
    </Switch>
  );
}

方法2

以下是我的主要路线文件:

export default function MainRouter() {
  return (
    <Router>
      <Route exact path="/" component={Home} />
      <Route exact path="/login" component={Login} />
      <Route exact path="/register" component={Register} />
      <Route exact path="/product/*" component={ProductRouter} />
    </Router>
  );
}

产品的子路线,如下ProductRouter.js文件中所示

export default function ProductRouter(props) {
  return (
    <Fragment>
      <Route exact path="/" component={ProductListing} />
      <Route
        exact
        path=":productId"
        component={ProductDetails}
      />
      <Route
        exact
        path=":productId/edit"
        component={ProductEdit}
      />
    </Fragment>
  );
}

下面是我检查的链接:

1 个答案:

答案 0 :(得分:3)

根路由上的

exact道具将排除所有子路由,因为根路由不再匹配,它们不会呈现。

Nesting Routes

您需要从根路线中删除exact道具(将其保留在本国路线上,以使其与始终不匹配)

export default function MainRouter() {
  return (
    <Router>
      <Route exact path="/" component={Home} />
      <Route path="/login" component={Login} />
      <Route path="/register" component={Register} />
      <Route path="/product" component={ProductRouter} />
    </Router>
  );
}

使用正确的路径前缀(您可以删除确切的prop,Switch仅呈现第一个匹配项

export default function ProductRouter(props) {
  console.log(props);
  const { match: { path } } = props;

  return (
    <Switch>
      // specify more specific path before less specific path
      <Route path={`${path}/:productId/edit`} component={ProductEdit} />
      <Route path={`${path}/:productId`} component={ProductDetails} />
      <Route path={path} component={ProductListing} />
    </Switch>
  );
}