You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React类组件Cannot destructure 'params' of 'this.props.match'报错如何解决

问题根因
  • 你当前使用的是React Router v6版本,该版本移除了类组件默认注入match/location/history路由属性的逻辑,所以无法直接通过this.props.match获取路由参数。同时Route组件的exact属性在v6中已经废弃,不需要再声明。
  • 路由配置存在拼写错误:你定义的组件名为ProfilesSinglePage,路由element属性中写的是ProfileSinglePage,少了s前缀,也会导致组件匹配异常。
解决方案

方案1:改为函数组件(v6官方推荐写法)

直接使用v6提供的useParams钩子获取路由参数,代码更简洁:

import { useParams, useEffect, useState } from 'react'
import axios from 'axios'

const ProfilesSinglePage = () => {
  const [details, setDetails] = useState('')
  // 直接获取路由参数
  const { id } = useParams()

  useEffect(() => {
    axios.get(`${Profiles}/${id}`)
      .then((res) => {
        setDetails(res.data)
      })
  }, [id])

  return (
    <React.Fragment>
      <h1>Profiles Details for id {id}</h1>
    </React.Fragment>
  )
}

修正后的路由配置:

<Routes>
  <Route path="/profiles" element={<ProfilesAllPage/>}/>
  <!-- 修正组件名,去掉废弃的exact属性 -->
  <Route path="/profile-details/:id" element={<ProfilesSinglePage/>}/>
</Routes>

方案2:保留类组件的实现方式

如果必须保留类组件写法,可以自定义一个高阶组件把路由参数注入到props中:

import { useParams } from 'react-router-dom'
import axios from 'axios'
import { Component } from 'react'

// 自定义高阶组件,注入路由参数
function withRouter(Component) {
  function ComponentWithRouterProp(props) {
    const params = useParams()
    return <Component {...props} match={{ params }} />
  }
  return ComponentWithRouterProp
}

class ProfilesSinglePage extends Component {
  constructor (props) {
    super (props)
    this.state={
      details:''
    };
  }
  render(){
    const {params} = this.props.match;
    return (
        <React.Fragment>
            <h1>Profiles Details for id {params.id}</h1>
        </React.Fragment>
    );
  };
  componentDidMount(){
    axios.get(`${Profiles}/${this.props.match.params.id}`)
    .then((res) => {
        this.setState({details:res.data})
    });
  };
};

// 导出时用高阶组件包裹
export default withRouter(ProfilesSinglePage)

路由配置修改逻辑和方案1一致即可。

内容的提问来源于stack exchange,提问作者Dester Ken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:06:03