【问题标题】:How do I configure axios in react to retrieve data with an objects id from an api?如何配置 axios 以响应从 api 检索具有对象 id 的数据?
【发布时间】:2021-12-30 13:23:35
【问题描述】:

我可以通过在 const [id] = useState(2) 中传递其 id 来访问该对象并获得希望的结果。但我想要的是当我导航到http://127.0.0.1:8000/view/2 时获取对象,而不必在 useState 中硬编码 id。如果我尝试使用 const [id] = props.match.params.id 我会收到一个错误,即 params 未定义。我如何从 URL http://127.0.0.1:8000/view/9 获取 id


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

【问题讨论】:

标签: javascript reactjs axios


【解决方案1】:

你应该在组件内部使用useParams钩子。

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>

【讨论】:

  • 使用 let id= parsInt(useParams(). Id) 也起到了作用。
  • @Eliya 如果id 不是数字类型怎么办?有人可以通过 url 导航,并且可以使用随机字符串而不是该 id 的数字。在这种情况下,react 应用程序将停止工作。类似http://127.0.0.1:8000/view/random-slug
猜你喜欢
  • 2019-06-02
  • 2020-06-18
  • 1970-01-01
  • 2021-03-27
  • 2020-07-09
  • 2022-12-20
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
相关资源
最近更新 更多