我正在尝试匹配url路径以执行动态路由,但是未在该路径上渲染组件。我在这里做什么错了?
到CollectionsOverview组件的路由正常。
购买Component.js:
onst ShopPage = ({ match }) => {
console.log(`Shop Component ${match.path}`);
return (
<div className='shop-page'>
<Switch>
<Route exact path={`/${match.path}`} component={CollectionsOverview} />
<Route
path={`/${match.path}/:collectionId`}
component={CollectionPage}
/>
</Switch>
</div>
);
};
export default ShopPage;
集合Component.js:
const CollectionPage = () => {
console.log(`Collection Page`);
return (
<div className='collection-page'>
<h2>Hello</h2>
</div>
);
};
结果:
答案 0 :(得分:0)
在/${match.path}/:collectionId
之前放置/${match.path}
路径,并从路由中删除exact
。
这是工作代码:https://codesandbox.io/s/react-router-dynamic-routing-r714l
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route, Switch, Link } from "react-router-dom";
const CollectionOverview = () => {
return (
<div>
<div>CollectionOverview</div> <br />
<Link to="/collection/1">To Collection 1</Link> <br />
<Link to="/collection/2">To Collection 2</Link> <br />
<Link to="/collection/3">To Collection 3</Link> <br />
<Link to="/collection/4">To Collection 4</Link> <br />
</div>
);
};
const CollectionPage = props => {
return <div>CollectionPage for ID: {props.match.params.id}</div>;
};
const HomeComponent = () => {
return <div>Home Component</div>;
};
function App() {
return (
<BrowserRouter>
<div>
<Link to="/">To Home</Link>
<br />
<Link to="/collection">To Collection Overview</Link>
<br />
</div>
<Switch>
<Route path="/collection/:id" component={CollectionPage} />
<Route path="/collection" component={CollectionOverview} />
<Route path="/" component={HomeComponent} />
</Switch>
</BrowserRouter>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);