React类组件读取this.props.match.params.login出现undefined报错如何解决
报错原因
该报错是因为你使用了React Router v6版本,该版本相较v5存在多处不兼容改动:v6 中通过Route的element属性渲染的组件,默认不会自动注入match、location、history这类路由相关props,所以User组件中读取的this.props.match为undefined,尝试读取params属性就会触发当前报错。
解决方法
因为你用的是类组件,无法直接调用React Router提供的hooks,推荐用以下两种方案解决:
方案1:自定义withRouter高阶组件包裹User类组件(推荐)
v6官方移除了原本内置的withRouter高阶组件,你可以手动实现:
- 新建
withRouter.js文件,代码如下:
import { useParams, useLocation, useNavigate } from 'react-router-dom'; export default function withRouter(Component) { function ComponentWithRouterProp(props) { const location = useLocation(); const navigate = useNavigate(); const params = useParams(); return <Component {...props} router={{ location, navigate, params }} />; } return ComponentWithRouterProp; }
- 修改User.js代码:
import React, { Component } from 'react' import withRouter from './withRouter' export class User extends Component { componentDidMount(){ // 从注入的router属性中读取params this.props.getUser(this.props.router.params.login); } render() { const{ name, avatar_url, location, bio, blog, login, html_url, followers, following, public_repos, public_gists, hireable, } = this.props.user; const {loading } = this.props; return <div>{name}</div> } } export default withRouter(User)
方案2:路由配置时直接传递params参数
如果不想额外封装高阶组件,也可以在App.js的路由配置中直接获取参数传递给User组件:
- 若App.js为函数组件,修改路由代码如下:
import { useParams } from 'react-router-dom' // 路由部分修改 <Route exact path='/user/:login' element={ <User getUser={this.getUser} user={user} loading={loading} login={useParams().login} /> }></Route>
- 修改User.js中读取参数的代码:
componentDidMount(){ this.props.getUser(this.props.login); }
内容的提问来源于stack exchange,提问作者Dev。
相关产品推荐
相关产品推荐

