【发布时间】:2021-12-15 15:24:11
【问题描述】:
当我尝试通过 API (http://thedogapi.com/) 显示身高和体重时,我收到错误消息:
TypeError: Cannot read properties of undefined (reading 'metric')
如果我评论“items.height.metric”,一切都很好,但我也必须展示这些结果。
在我获得 ID 之前的一个页面中,当我单击列表中的一个项目时,我会进入第二个页面,显示类似“http://localhost:3000/config/?id=2”(所以,我点击了第二个项目)。 GitHub:https://github.com/fvrabelo/tiroNewDogApi 有什么帮助吗?爱你们
import {React} from 'react'
import {useEffect, useState} from 'react';
import {Link} from 'react-router-dom'
const Page = () =>{
// identifica ID na url
const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id');
// fetch da raca baseado no ID passado pela url
const [items, setItems] = useState([])
useEffect(() => {
const getBreeds = async () =>{
const res = await fetch(
`https://api.thedogapi.com/v1/breeds/${id}`
);
const data = await res.json();
setItems(data)
}
getBreeds()
}, [])
//fetch da imagem
function getImage(imageId) {
fetch(`https://api.thedogapi.com/v1/images/${imageId}`)
.then(r =>r.json())
.then(response=> {
const data = response
document.querySelector(".image").src = data.url;
})
}
return(
<div className=""
style={{"display": "flex",
"position":"relative",
"justify-content": "center",
"align-items": "center",
'flex-direction': "column",
"maxWidth":"100%",
"maxHeight":"100%"}}>
<h6 className="card-subtitle mb-2 text-muted text-center" style={{"marginTop":"5px"}}>Breed name</h6>
<h5 className="card-title text-center">{items.name}</h5>
<h6 className="card-subtitle mb-2 text-muted text-center" style={{"marginTop":"5px"}}>Bred for</h6>
<h5 className="card-title text-center">{items.bred_for}</h5>
<h6 className="card-subtitle mb-2 text-muted text-center" style={{"marginTop":"5px"}}>Group</h6>
<h5 className="card-title text-center">{items.breed_group}</h5>
<h6 className="card-subtitle mb-2 text-muted text-center" style={{"marginTop":"5px"}}>Temperament</h6>
<h5 className="card-title text-center">{items.temperament}</h5>
<h6 className="card-subtitle mb-2 text-muted text-center" style={{"marginTop":"5px"}}>Life span</h6>
<h5 className="card-title text-center">{items.life_span}</h5>
<h6 className="card-subtitle mb-2 text-muted text-center" style={{"marginTop":"5px"}}>Height</h6>
<h5 className="card-title text-center">{items.height.metric}</h5>
<h6 className="card-subtitle mb-2 text-muted text-center" style={{"marginTop":"5px"}}>Weight</h6>
<h5 className="card-title text-center">{items.weight.metric}</h5>
<img className ="image"
src={getImage(items.reference_image_id) }
style={{ "maxHeight": "300px", "maxWidth": "300px", "marginBottom":"15px" }}/>
<Link to="/" className="btn btn-primary">Home</Link>
</div>
);
}
export default Page;
<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>
现在我有这样的事情: enter image description here
【问题讨论】:
标签: javascript reactjs json api dom