未捕获类型错误:无法读取未定义的属性(读取“params”) 无法导航到 id 任何人都可以帮忙吗? 我正在 Django 作为后端,并以 React 作为前端
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
});
console.log(res.data)
})
}
render(){
return(
<Card title={this.state.article.title} >
<p>{this.state.article.content }</p>
</Card>
)
}
}```
TypeError: Cannot read properties of undefined (reading 'params') Unabel to navigate to id can anyone help?
i am working on react + django. My data from server in list is showing but when i try to navigate to particular data id it shows error
这应该是前端问题。
1-) 在课程开头添加以下代码行:
import { useParams } from 'react-router-dom';
2-) 然后将此函数添加到您的类上方(准确复制):
export function withRouter(Children){
return(props)=>{
const match = {params: useParams()};
return <Children {...props} match = {match}/>
}
}
3-) 接下来,将类定义更改为:
class ArticleDetail extends Component
4-) 在课程末尾添加以下代码行:
export default withRouter(ArticleDetail);
参考:https://stackoverflow.com/a/75304487/11897778
如果不起作用,请提供有关错误的更多详细信息,是正在发出 API 请求还是在发出 API 请求之前失败?
这对我有用 感谢冯耶稣的帮助
import React from "react";
import axios from 'axios';
import {Card} from "antd";
import { useParams } from "react-router-dom";
export function withRouter(Children){
return(props)=>{
const match = {params: useParams()};
return <Children {...props} match = {match}/>
}
}
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
});
console.log(res.data)
})
}
render(){
return(
<Card title={this.state.article.title} >
<p>{this.state.article.content }</p>
</Card>
)
}
}
export default withRouter(ArticleDetail);
从“../products”导入产品;导入 { useParams } 来自 “反应路由器-dom”;
function ProductScreen() { const match = { params: useParams() };
const Product = products.find((p) => p._id === match.params.id);
返回 {产品.名称}; }