我正在尝试在 Reactjs 中实现子/嵌套路由,下面是我发现的用于嵌套子路由的 2 种方法,但父路由可以正常工作,而父组件的子路由则不能。
下面是路由的工作原理:
/ => 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]
方法一
下面是我的主路由文件:
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>
);
}
和 Product 的子路由,如下面的 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>
);
}
方法二
下面是我的主路由文件:
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>
);
}
和 Product 的子路由,如下面的 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>
);
}
以下是我检查过的链接:
最佳答案
根路由上的
exact
属性将排除任何子路由,它们不会呈现,因为根路由不再匹配。
您需要从根路由中删除 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>
);
}
使用正确的路径前缀(你可以移除 exact 属性,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>
);
}
关于javascript - react 子嵌套路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62190437/