Puedo acceder al objeto pasando su id en const [id] = useState(2) y obtengo los resultados esperados. Pero lo que quiero es cuando navego a http://127.0.0.1:8000/view/2 obtengo el objeto sin tener que codificar la identificación en useState. Si trato de usar const [id] = props.match.params.id, obtengo un error que indica que los parámetros no están definidos. ¿Cómo obtengo la identificación de la URL http://127.0.0.1:8000/view/9?
//I have this route in App.js: <Route exact path="view/:id" component={<ViewPage/>} /> //In ViewPage.js i have: import React,{useEffect, useState} from 'react'; import axios from 'axios'; import ViewPageUI from './ViewPageUi'; function ViewPage(props) { const [tour, setTour] = useState({}) const [id] = useState(2) // 2 is the id of an object useEffect(() => { axios.get(`http://127.0.0.1:8000/api/${id}`) .then(res => { console.log(res) setTour(res.data) }) .catch(err => { console.log(err) }) },[id]); return ( <div> <h2>View Tour</h2> <ViewPageUI key={tour.id} name={tour.name} { *other code*} /> </div> ) ; }Debe usar el gancho useParams dentro del componente.
import React,{useEffect, useState} from 'react'; import { useParams } from 'react-router-dom'; import axios from 'axios'; import ViewPageUI from './ViewPageUi'; function ViewPage(props) { const [tour, setTour] = useState({}) const { id } = useParams() useEffect(() => { if ( id ) { axios.get(`http://127.0.0.1:8000/api/${id}`) .then(res => { console.log(res) setTour(res.data) }) .catch(err => { console.log(err) }) } }, [ id ]); return ( <div> <h2>View Tour</h2> <ViewPageUI key={tour.id} name={tour.name} /> {/* other code */} </div> ); } <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>