React+Django项目报错:Cannot read properties of undefined (reading 'params')
解决React路由跳转详情页时
Cannot read properties of undefined (reading 'params')错误 这个错误的核心原因是你的ArticleDetail组件没有获取到路由的match属性,导致this.props.match为undefined,进而无法读取params.id。下面根据你使用的React Router版本给出针对性解决方案:
如果你用的是React Router v5
方案1:确保组件被<Route>直接渲染
检查你的路由配置,必须让ArticleDetail作为<Route>的component属性值,而不是作为普通子组件嵌套在其他组件中:
import { Route } from 'react-router-dom'; import ArticleDetail from './ArticleDetail'; // 路由配置示例 <Route path="/article/:id" component={ArticleDetail} />
这样React Router会自动把match、location、history等路由相关属性注入到组件的props中。
方案2:用withRouter高阶组件包裹组件
如果你的ArticleDetail是作为其他组件的子组件使用(而非直接被<Route>渲染),需要用withRouter包裹组件来注入路由属性:
import { withRouter } from 'react-router-dom'; import axios from 'axios'; import { Card } from 'antd'; class ArticleDetail extends React.Component{ state={ article:{} } componentDidMount(){ const id = this.props.match.params.id; axios.get(`http://127.0.0.1:8000/api/${id}`) .then(res => this.setState({ article: res.data })) } render(){ return( <Card title={this.state.article.title} > <p>{this.state.article.content }</p> </Card> ) } } // 用withRouter包裹后导出 export default withRouter(ArticleDetail);
如果你用的是React Router v6
React Router v6移除了withRouter,类组件无法直接获取路由参数,可通过以下两种方式解决:
方案1:将类组件转为函数组件,使用useParams钩子
这是v6推荐的方式,函数组件可以直接用路由钩子获取参数:
import { useParams, useEffect, useState } from 'react-router-dom'; import axios from 'axios'; import { Card } from 'antd'; function ArticleDetail() { const [article, setArticle] = useState({}); const { id } = useParams(); // 直接获取id参数 useEffect(() => { axios.get(`http://127.0.0.1:8000/api/${id}`) .then(res => setArticle(res.data)) }, [id]); return( <Card title={article.title} > <p>{article.content }</p> </Card> ) } export default ArticleDetail;
方案2:用函数组件做包装器,传递参数给类组件
如果不想修改类组件结构,可以写一个函数组件作为中间层,用useParams获取参数后传递给类组件:
import { useParams } from 'react-router-dom'; import axios from 'axios'; import { Card } from 'antd'; // 原类组件 class ArticleDetailClass extends React.Component{ state={ article:{} } componentDidMount(){ const { id } = this.props; axios.get(`http://127.0.0.1:8000/api/${id}`) .then(res => this.setState({ article: res.data })) } render(){ return( <Card title={this.state.article.title} > <p>{this.state.article.content }</p> </Card> ) } } // 包装函数组件 function ArticleDetail() { const { id } = useParams(); return <ArticleDetailClass id={id} />; } export default ArticleDetail;
额外检查点
- 确认路由路径定义了
:id参数,比如path="/article/:id",而非无参数的路径; - 跳转详情页时,确保通过
<Link>或路由方法传递了正确的ID,例如:<Link to={`/article/${item.id}`}>查看详情</Link>
内容的提问来源于stack exchange,提问作者M Junaid
相关产品推荐
相关产品推荐

