如何在React Route中同时传递Props和Match参数给路由组件
问题原因
- 你在
Route的component属性内定义的箭头函数收到了路由自动传入的match/location/history等路由参数,但你没有将这些参数透传给ItemInfo组件,导致组件拿不到match对象 - 你自定义传入的
title是直接作为ItemInfo的根级属性传递的,不需要从props属性下读取,你对组件参数的解构写法有误
解决方法
方法1:透传路由参数(适配React Router v5)
推荐使用Route的render属性代替component属性传递内联函数,避免组件不必要的卸载重挂载,同时将路由参数透传给目标组件:
<Route path='/shop/:id' render={routeProps => <ItemInfo {...routeProps} title='Props through component' />} />
对应ItemInfo组件正确的解构写法:
// 所有传入的属性都在第一个参数的根级,直接解构即可 const ItemInfo = ({ title, match }) => { console.log(title); // 正常读取自定义属性 console.log(match.params.id); // 正常读取路由参数 }
方法2:使用路由Hook(适配React Router v5/v6,更简洁)
不需要手动透传路由参数,直接在组件内用useParamsHook获取路由参数:
路由配置可简化为:
// React Router v6写法 <Route path='/shop/:id' element={<ItemInfo title='Props through component' />} /> // React Router v5写法 <Route path='/shop/:id'> <ItemInfo title='Props through component' /> </Route>
ItemInfo组件代码:
import { useParams } from 'react-router-dom'; const ItemInfo = ({ title }) => { // 直接通过Hook获取路由id参数 const { id } = useParams(); console.log(title); console.log(id); }
内容的提问来源于stack exchange,提问作者Xelphin
相关产品推荐
相关产品推荐

