Var*_*eja 3 javascript reactjs react-router
我正在尝试在 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]
Run Code Online (Sandbox Code Playgroud)
以下是我的主要路线文件:
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>
);
}
Run Code Online (Sandbox Code Playgroud)
和 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>
);
}
Run Code Online (Sandbox Code Playgroud)
以下是我的主要路线文件:
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>
);
}
Run Code Online (Sandbox Code Playgroud)
和 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>
);
}
Run Code Online (Sandbox Code Playgroud)
以下是我检查过的链接:
exact
根路由上的 prop 将排除任何子路由,它们不会渲染,因为根路由不再匹配。
您需要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>
);
}
Run Code Online (Sandbox Code Playgroud)
使用正确的路径前缀(您可以删除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>
);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2436 次 |
最近记录: |