简体   繁体   中英

How do I configure axios in react to retrieve data with an objects id from an api?

I am able to access the object by passing its id in the const [id] = useState(2) and get the results hoped for. But want I is when I navigate to http://127.0.0.1:8000/view/2 i get the object without having to hard code the id in the useState. If I try to use const [id] = props.match.params.id i get an error that params is undefined. How do i get the id from the 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}

You should use useParams hook inside the component.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM