[英]React: Pass parameters using React-Router v6
App.js where all my Routes are declared: App.js 声明了我的所有路由:
function App() {
return (
<div className="App">
<Routes>
<Route path="/">
<Route index element={<Homepage />} />
<Route path="settings" element={<Settings />} />
<Route path="report/:runId" element={<TestReport />} />
<Route path="report/:runId/:specFileName" element={<SpecFile />} />
</Route>
</Routes>
</div>
)
}
Here I have the Link to (in my current case) /report/2/Login where I want to pass some parameters:在这里,我有指向(在我目前的情况下)/report/2/Login 的链接,我想在其中传递一些参数:
<TableCell>
<Link
to={`/report/${this.props.runId}/${specFile.name}`}
state={{ testcases: this.props.testcases }}
>
{specFile.name}
</Link>
</TableCell>
Here I want to access my parameters:在这里我想访问我的参数:
import { useLocation } from "react-router-dom";
export default function SpecFile() {
const location = useLocation();
const { from } = location.specFile.name;
console.log(from); // Should print "Login" instead gives Error Message: Cannot read properties of undefined (reading 'name')
}
There is a hook in react-router-6 for this. react-router-6 中有一个钩子。
import { useSearchParams } from 'react-router-dom';
and then use it like:然后像这样使用它:
const [searchParams] = useSearchParams();
location.specFile.name;
is invalid and breaks because the location
object doesn't have any specFile
property.无效并中断,因为location
对象没有任何specFile
属性。
interface Location { pathname: string; search: string; hash: string; state: unknown; key: string; }
Access the passed route state on location.state
, specifically on location.state?.testcases
.在location.state
上访问通过的路由状态,特别是在location.state?.testcases
上。
For the given route <Route path="report/:runId/:specFileName" element={<SpecFile />} />
the SpecFile
component should use the useParams
hook to access the route path params runId
and specFileName
.对于给定的路由<Route path="report/:runId/:specFileName" element={<SpecFile />} />
, SpecFile
组件应该使用useParams
挂钩来访问路由路径参数runId
和specFileName
。
Example:例子:
import { useLocation, useParams } from "react-router-dom";
export default function SpecFile() {
const { id, specFileName } = useParams();
const { state } = useLocation();
const { testcases } = state || {};
useEffect(() => {
console.log({ id, specFileName, testcases });
}, [id, specFileName, testcases]);
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.