【发布时间】: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>
) ;
}
【问题讨论】:
-
useParams() 检查这个钩子
-
Grate,useParams() 实际上完成了工作,非常感谢。
标签: javascript reactjs axios