问题:
从项目列表中导航到详细信息页面,传递所选的详细信息
解决方案:
使用React Router在页面之间传递数据主要有以下三个选项:
选项1:传递路由状态
发送路线中的项目 ID状态:
v6(声明式):
<Link to="/home/userDetails" state={{ infoId: info.id }}>...</Link>
v6(命令式):
import { useNavigate } from "react-router-dom"; const navigate = useNavigate(); navigate("/home/userDetails", { state: { infoId: info.id } });
v5 (声明式):
<Link to={{ pathname: '/home/userDetails', state: { infoId: info.id } }}>...</Link>
v5 (命令式):
import { useHistory } from "react-router-dom"; const history = useHistory(); history.push({ pathname: '/home/userDetails', state: { infoId: info.id } });
接收目的地的状态组件:
v6:
const { state: { infoId } = {} } = useLocation();
v5:
if (props.location && props.location.state && props.location.state.infoId) { // Access info ID }
选项 2:传递一些东西在 URL 路径
包含该项目URL路径中的ID:
<Link to={`/home/userDetails/${info.id}`}>...</Link>
接收目标组件中的参数:
v6:
const { infoId } = useParams();
v5 :
const infoId = props.match.params.infoId;
选项3:在 URL 查询字符串中传递某些内容
将项目 ID 附加到 URL 查询字符串:
v6(声明式):
<Link to={{ pathname: '/home/userDetails', search: `?infoId=${info.id}` }}>...</Link>
v6 (命令式):
import { useNavigate } from "react-router-dom"; const navigate = useNavigate(); navigate({ pathname: '/home/userDetails', search: `?infoId=${info.id}` });
v5(声明式):
<Link to={{ pathname: '/home/userDetails', search: `?infoId=${info.id}` }}>...</Link>
v5(命令式):
import { useHistory } from "react-router-dom"; const history = useHistory(); history.push({ pathname: '/home/userDetails', search: `?infoId=${info.id}` });
在目的地接收查询参数组件:
v6:
const [searchParams] = useSearchParams(); const infoId = searchParams.get("infoId");
v5:
if (props.location && props.location.search) { const searchParams = new URLSearchParams(props.location.search); const infoId = searchParams.get("infoId"); }
以上是如何在 React Router 页面之间高效传递数据?的详细内容。更多信息请关注PHP中文网其他相关文章!