在 react-router
中实现页面跳转并传递参数,可以通过以下几种方式来完成:
1. 通过 URL 参数传递
定义路由时:
在定义路由时,可以使用 URL 参数。例如:
<Route path="/user/:id" component={User} />
跳转时:
使用 useHistory
或 useNavigate
(在 React Router v6 中)进行跳转时,可以将参数添加到 URL 中:
import { useHistory } from 'react-router-dom'; // React Router v5
function RedirectToUser() {
const history = useHistory();
const handleClick = () => {
history.push(`/user/123`); // 跳转到 /user/123
};
return <button onClick={handleClick}>Go to User 123</button>;
}
import { useNavigate } from 'react-router-dom'; // React Router v6
function RedirectToUser() {
const navigate = useNavigate();
const handleClick = () => {
navigate(`/user/123`); // 跳转到 /user/123
};
return <button onClick={handleClick}>Go to User 123</button>;
}
接收参数:
在目标组件中,可以使用 useParams
钩子(在 React Router v6 中也是 useParams
)来接收 URL 参数:
import { useParams } from 'react-router-dom';
function User() {
const { id } = useParams();
return <div>User ID: {id}</div>;
}
2. 通过查询字符串传递
跳转时:
可以将参数作为查询字符串添加到 URL 中:
import { useHistory } from 'react-router-dom'; // React Router v5
function RedirectToUser() {
const history = useHistory();
const handleClick = () => {
history.push(`/user?id=123`); // 跳转到 /user?id=123
};
return <button onClick={handleClick}>Go to User</button>;
}
import { useNavigate } from 'react-router-dom'; // React Router v6
function RedirectToUser() {
const navigate = useNavigate();
const handleClick = () => {
navigate(`/user?id=123`); // 跳转到 /user?id=123
};
return <button onClick={handleClick}>Go to User</button>;
}
接收查询参数:
可以使用 URLSearchParams
来获取查询参数:
import { useLocation } from 'react-router-dom';
function User() {
const { search } = useLocation();
const params = new URLSearchParams(search);
const id = params.get('id');
return <div>User ID: {id}</div>;
}
3. 通过状态传递
跳转时:
可以将参数作为状态传递:
import { useHistory } from 'react-router-dom'; // React Router v5
function RedirectToUser() {
const history = useHistory();
const handleClick = () => {
history.push({
pathname: '/user',
state: { id: 123 }
});
};
return <button onClick={handleClick}>Go to User</button>;
}
import { useNavigate } from 'react-router-dom'; // React Router v6
function RedirectToUser() {
const navigate = useNavigate();
const handleClick = () => {
navigate('/user', { state: { id: 123 } });
};
return <button onClick={handleClick}>Go to User</button>;
}
接收状态:
在目标组件中,可以通过 useLocation
钩子获取传递的状态:
import { useLocation } from 'react-router-dom';
function User() {
const location = useLocation();
const id = location.state?.id;
return <div>User ID: {id}</div>;
}