我在客户端应用程序中使用了 react 和 react-router。我似乎无法弄清楚如何从以下 URL 获取以下查询参数:
http://xmen.database/search#/?status=APPROVED&page=1&limit=20
我的路线如下所示(我知道这条路径完全是错误的):
var routes = ( <Route> <DefaultRoute handler={SearchDisplay}/> <Route name="search" path="?status=:status&page=:page&limit=:limit" handler={SearchDisplay}/> <Route name="xmen" path="candidate/:accountId" handler={XmenDisplay}/> </Route> );
我的路线运行正常,但我不知道如何格式化路径以获取我想要的参数。非常感谢任何帮助!
要在 React Router 中处理查询参数,您无需在路径中指定它们。相反,您可以使用useLocationiuseHistory``useSearchParams
useLocation
useHistory``useSearchParams
react-router-dom
npm install react-router-dom
``` import React from ‘react’; import { BrowserRouter as Router, Route, Switch } from ‘react-router-dom’; import SearchDisplay from ‘./SearchDisplay’; import XmenDisplay from ‘./XmenDisplay’;
const App = () => (
<<Router> <Switch> <Route exact path="/" component={SearchDisplay} /> <Route path="/search" component={SearchDisplay} /> <Route path="/candidate/:accountId" component={XmenDisplay} /> </Switch> </Router>
);
expor
<export default App;
```
SearchDisplay
``` import React from ‘react’; import { useLocation } from ‘react-router-dom’;
const useQuery = () => { return new URLSearchParams(useLocation().search); }
const SearchDisplay = () => { const query = useQuery(); const status = query.get(‘status’); const page = query.get(‘page’);
const limit = query.get(‘limit’);
retur
return (
<div> <div> <h1>Search Results</h1> <p>Status: {status}</p> <p>Page: {page}</p> <p>Limit: {limit}</p> </div> );
}
</
export default SearchDisplay; ```
``` import React from ‘react’; import { BrowserRouter as Router, Routes, Route } from ‘react-router-dom’; import SearchDisplay from ‘./SearchDisplay’;
im import XmenDisplay from ‘./XmenDisplay’;
cons
<<Router> <Routes> <Route path="/" element={<SearchDisplay />} /> <Route path="/search" element={<SearchDisplay />} /> <Route path="/candidate/:accountId" element={<XmenDisplay />} /> </Routes> </Router>
e
)
< <Route path="/" element={<SearchDisplay / <Route path="/" element={<SearchDi <Route path="/" element={<S <Route path="/search" element={<SearchDisplay <Route path="/search" element={<SearchD <Route path="/candidate/:accountId" element={<XmenDisplay / <Route path="/candidate/:accountId" element={<XmenDis <Route path="/candidate/:accountId" element={<X <
export default App; ```
useSearchParams
``` import React from ‘react’;
impo import { useSearchParams } from ‘react-router-dom’;
const SearchDisplay = () => {
const [searchParams] = useSearchParams();
c
const status = searchParams.get(‘status’);
con
const page = searchParams.get(‘page’);
co
const limit = searchParams.get(‘limit’);
ret
<div> <div> <h1> <div> < <div>
Status: {status}
Page: {page}
Limit: {limit}
exp
); <p>S <p> </
URLSearchParams
React Router v6:useSearchParams hook
这两种方法都允许您从 URL 读取查询参数,而无需将它们包含在路径定义中。