在React Router中设置参数,您可以使用以下两种方法:
方法1:使用动态路由
id
的参数,您可以在<Route>
组件中定义它:import { BrowserRouter as Router, Route } from 'react-router-dom';
import YourComponent from './YourComponent';
function App() {
return (
<Router>
<Route path="/your-path/:id" component={YourComponent} />
</Router>
);
}
export default App;
useParams
钩子获取参数的值。例如:import React from 'react';
import { useParams } from 'react-router-dom';
function YourComponent() {
const { id } = useParams();
return (
<div>
<h1>参数值:{id}</h1>
</div>
);
}
export default YourComponent;
方法2:使用查询参数
import { BrowserRouter as Router, Route } from 'react-router-dom';
import YourComponent from './YourComponent';
function App() {
return (
<Router>
<Route path="/your-path" component={YourComponent} />
</Router>
);
}
export default App;
Link
组件或useHistory
钩子添加查询参数。例如:import React from 'react';
import { Link } from 'react-router-dom';
function Navigation() {
return (
<nav>
<Link to="/your-path?id=1">设置参数</Link>
</nav>
);
}
export default Navigation;
或者:
import React from 'react';
import { useHistory } from 'react-router-dom';
function YourComponent() {
const history = useHistory();
const handleClick = () => {
history.push('/your-path?id=1');
};
return (
<div>
<button onClick={handleClick}>设置参数</button>
</div>
);
}
export default YourComponent;
useLocation
钩子获取查询参数的值。例如:import React from 'react';
import { useLocation } from 'react-router-dom';
function YourComponent() {
const location = useLocation();
const searchParams = new URLSearchParams(location.search);
const id = searchParams.get('id');
return (
<div>
<h1>参数值:{id}</h1>
</div>
);
}
export default YourComponent;
这两种方法都可以实现在React Router中设置参数的目的。动态路由方法适用于参数是路由路径的一部分的情况,而查询参数方法适用于参数是URL中的查询字符串的情况。
领取专属 10元无门槛券
手把手带您无忧上云