react-router-dom V6类组件如何获取<Link>传递的路由参数
解决方案
react-router-dom v6 仅提供 Hook 形式的路由能力,类组件无法直接调用 Hook,我们可以通过「函数组件桥接」的方式,将 Hook 拿到的路由参数以 props 形式传递给类组件使用,以下是两种可落地的实现方案:
方案1:直接修改路由配置(单次使用推荐)
不需要新增额外文件,直接修改 App.js 中的路由定义即可:
// 首先在App.js顶部导入useParams import { useParams } from 'react-router-dom' function App() { return ( <BrowserRouter> <NAVBAR /> <Routes> <Route path="/" element={ <SHOW_OPTIONS />} /> {/* 仅修改这一条路由的element配置 */} <Route path="/view_list/:list_id" element={ (() => { const params = useParams() // 将路由参数以props形式传递给类组件 return <SHOW_LIST list_id={params.list_id} /> })() } /> <Route path="/authorize" element={ <AUTHORIZE_ITEM /> } /> </Routes> </BrowserRouter> ); }
修改后直接在 SHOW_LIST 组件中通过 this.props.list_id 即可拿到参数,调整 componentDidMount 逻辑即可:
componentDidMount() { // 直接用props里的参数调用接口 getListData(this.props.list_id) .then(res => res.json()) .then(data => { console.log(data); this.setState({items: data}); }) .catch(err => { console.log(err); }); }
方案2:自定义withRouter高阶组件(多类组件复用推荐)
如果项目里有多个类组件需要使用路由能力,可以封装通用的 withRouter 高阶组件,一次性注入所有路由相关能力(参数、导航、路径信息等):
- 新增
withRouter.js文件:
import { useParams, useLocation, useNavigate } from 'react-router-dom' export function withRouter(Component) { function ComponentWithRouterProp(props) { const location = useLocation() const navigate = useNavigate() const params = useParams() // 将所有路由相关能力挂载到props的router属性上 return <Component {...props} router={{ location, navigate, params }} /> } return ComponentWithRouterProp }
- 修改 SHOW_LIST 组件的导出逻辑:
import { withRouter } from './withRouter' class SHOW_LIST extends Component { // 原有逻辑不变 componentDidMount() { // 从router属性中获取路由参数 const list_id = this.props.router.params.list_id getListData(list_id) // 原有接口调用逻辑不变 } } // 用高阶组件包裹后导出 export default withRouter(SHOW_LIST)
额外注意点
你原有 SHOW_LIST 的 render 方法存在语法错误:直接返回 {this.buildList()} 会触发语法报错,去掉外层的花括号,直接写 return this.buildList() 即可。
内容的提问来源于stack exchange,提问作者backward forward
相关产品推荐
相关产品推荐

