React Router使用Link跳转时传递Props的问题求助
如何通过React Router的Link组件向目标路由组件传递props?
你遇到的问题很典型——React Router的Link组件并不会把你自定义的id属性直接传递给目标路由组件。路由组件的props是由React Router统一注入的,包含match、location、history这些路由相关对象,而不是你在Link上添加的自定义属性。下面给你几种可行的解决方案:
方法1:通过URL参数传递(推荐,URL可见且刷新页面不丢失)
这种方式是最常用的,把参数放在URL路径里:
- 修改路由配置,添加URL参数占位符:
<Route path="/account/:id" component={Account}/>
- 更新Link组件,把id拼接到URL路径中:
<Link to={`/account/${1234}`}>点击跳转</Link>
- 在Account组件中获取参数:
通过props.match.params.id就能拿到传递的id值:
export default class Account extends Component { constructor(props) { super(props); const accountId = props.match.params.id; alert(accountId); // 这里会弹出1234 } }
方法2:通过location.state传递(URL不可见,刷新页面会丢失)
如果你不想让参数出现在URL里,可以用这种方式:
- 更新Link组件,通过
to的对象形式传递state:
<Link to={{ pathname: "/account", state: { id: 1234 } }}>点击跳转</Link>
- 在Account组件中获取参数:
通过props.location.state.id获取,但要注意如果用户直接刷新页面,state会被清空,所以最好加个判断:
export default class Account extends Component { constructor(props) { super(props); const accountId = props.location.state?.id; // 使用可选链避免报错 alert(accountId); // 正常跳转时弹出1234,刷新后弹出undefined } }
额外说明(React Router v6)
如果你现在升级到了React Router v6,路由配置和参数获取方式会有变化:
- 路由配置改为
<Route path="/account/:id" element={<Account />}/> - Link写法和v5一致,但获取参数需要用
useParams()钩子(函数组件),类组件则需要用高阶组件包裹来获取参数。
内容的提问来源于stack exchange,提问作者Craig
相关产品推荐
相关产品推荐

