This is Undefined in React Hooks

Asked

Viewed 397 times

-1

Hello, I’m creating a JS system using React Hooks, but I came across a problem when I use <Route exact path ="/produto/:idProduto" component={Quiz}/>

we were able to capture the id with const {id} = this.props.match.params (storing within a variable)

but this usually works in an example "Component class":

class Quiz extends Component{
    constructor(props){
        super(props)
        this.state = {  }
    }

    componentDidMount(){
        const {id} = this.props.match.params
        console.log(id)
    }

    render(){
        return(
            <div>
                oi
            </div>
        )
    }
}
export default Quiz

in this example is printed in the console the id that is in the url, all right. but when I use React Hooks, it appears "this is not defined" same example with Hooks:

import React, { useEffect } from 'react'

function Exemplo(){

    useEffect(()=>{
        const {id} = props.match.params
        console.log(id)
    },[])

    return(
        <div>
            oi
        </div>
    )
}
export default Exemplo

error:

Typeerror: this is Undefined

1 answer

1


You must receive props as a parameter of hook (just as you get it in the class builder) and use it without the this:

function Exemplo(props){
  const {id} = props.match.params

  // ...
}
  • Thanks bro, it worked!! (I took out this)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.