如何创建可以同时处理零参数、一个参数、另一个参数或两个参数的路径。
例如:
/offers /offers/q-shoes /offers/London /offers/London/q-shoes
我正在尝试以这种方式实现它,不幸的是,在这种情况下,路径/offers/London没有被捕获
import React from 'react';
import pathToRegexp from 'path-to-regexp';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { Home, Browse } from './Pages';
const re = pathToRegexp('/offers/:location?/q-:search?');
const App = () => (
<Router>
<Switch>
<Route path={re}>
<Browse />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</Router>
);
export default App;发布于 2021-10-18 10:17:32
创建指向同一组件的多个路径:
<Route path="/offers/q-shoes">
<RelevantComponentHere />
</Route>
<Route path="/offers/London">
<RelevantComponentHere />
</Route>
<Route path="/offers/London/q-shoes">
<RelevantComponentHere />
</Route>
<Route path="/offers/q-shoes/London">
<RelevantComponentHere />
</Route>正如您可能知道的那样,这并不理想。相反,您可以将路径转换为实际的URL参数(例如"/offers?q-shoes=true&London=true")。在这种情况下,您只有一条路径:
<Route path="/offers">
<RelevantComponentHere />
</Route>然后,您可以使用useParams或useLocation挂钩来查找相关参数并使用它们。
https://stackoverflow.com/questions/69614024
复制相似问题