reactjs TypeError:Cannot read properties of undefined(阅读'params')Django + React

vi4fp9gy  于 2023-06-05  发布在  React
关注(0)|答案(2)|浏览(382)

未捕获的类型错误:无法读取未定义的属性(正在阅读'params')Unabel导航到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
5n0oy7gb

5n0oy7gb1#

这应该是一个前端问题。
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请求之前失败?

j9per5c4

j9per5c42#

这对我很有用谢谢冯耶稣的帮助

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);

相关问题