如何在React不同路由组件之间传递选中的国家编码参数
方案1:使用React Router内置的Link state传参(无需修改路由配置,最快捷)
这个方案适合不需要把国家编码暴露在URL、不需要支持页面刷新/链接分享的场景。
修改步骤
- 修改CountryList组件的Link配置
找到CountryList里遍历渲染Link的部分,把原来的字符串形式to改成对象格式,携带state参数:
<Link style={{ display: "block" }} to={{ pathname: '/regions', state: { countryCode: item.code } }} > {item.name} </Link>
- 在RegionList组件中接收参数
导入useLocation钩子,获取传递的国家编码,注意加兜底逻辑避免直接访问路由时报错:
import React from "react"; import { Link, useLocation } from "react-router-dom"; import { BsSearch } from "react-icons/bs"; export default function RegionList(): JSX.Element { const location = useLocation(); // 可选链+默认值处理 const countryCode = location.state?.countryCode ?? ''; // 拿到countryCode后发起GET请求 React.useEffect(() => { if (countryCode) { // 替换为你的实际接口请求逻辑 fetch(`/your/api/regions?countryCode=${countryCode}`) .then(res => res.json()) .then(data => { // 处理返回的区域列表 }) } }, [countryCode]) // 原有组件代码保持不变 }
方案2:使用动态路由参数(更推荐,支持页面刷新、链接分享)
这个方案会把国家编码暴露在URL中,比如用户点击美国后跳转到/regions/US,刷新页面参数不会丢失,还可以直接分享链接给其他人访问。
修改步骤
- 修改区域模块的路由配置
调整RegionsRoute的路由规则,增加动态参数占位符:
import { Route, Routes } from "react-router-dom"; import React from "react"; import RegionComponent from "../components/RegionComponent"; export class RegionsRoute extends React.Component { render() { return ( <Routes> {/* 增加countryCode动态参数 */} <Route path="/:countryCode" element={<RegionComponent />} /> </Routes> ); } }
- 修改CountryList组件的跳转链接
把Link的to路径改成携带国家编码的格式:
<Link style={{ display: "block" }} to={`/regions/${item.code}`} > {item.name} </Link>
- 在RegionList组件中接收参数
导入useParams钩子获取动态参数:
import React from "react"; import { Link, useParams } from "react-router-dom"; import { BsSearch } from "react-icons/bs"; export default function RegionList(): JSX.Element { const { countryCode } = useParams(); // 拿到countryCode后发起请求 React.useEffect(() => { if (countryCode) { // 替换为你的实际接口请求逻辑 fetch(`/your/api/regions?countryCode=${countryCode}`) .then(res => res.json()) .then(data => { // 处理返回的区域列表 }) } }, [countryCode]) // 原有组件代码保持不变 }
其他可选方案
如果项目后续有更多跨路由全局状态共享的需求,也可以选择以下实现方式:
- 引入Zustand/Jotai等轻量状态管理库:定义全局存储国家编码的store,在CountryList点击时写入store,RegionList中从store读取数据
- 用localStorage/sessionStorage:点击国家时把编码写入本地存储,进入RegionList时读取后清除,适合临时数据传递场景
注意:两种核心方案都建议增加参数合法性校验,如果获取不到合法的国家编码,可以引导用户返回国家列表重新选择。
内容的提问来源于stack exchange,提问作者amr369
相关产品推荐
相关产品推荐

