[英]Access Data in nested JSON API Object in react
我在 JSON-Api 中有此数据,但我的反应应用程序不想让从嵌套对象中获取值。
[
{
"_id": "61715a5351b12fadc073940a",
"name": "Betty",
"owner": {
"_id": "614323ed282bfd3e68bbaf4f",
"name": "Kirk Douglas",
"email": "kirk@example.com",
"__v": 0
},
"addressText": "Some cool street",
"addressNumber": "91",
"zipCode": "34567",
"city": "Washington"
"__v": 0
},
{
"_id": "61715cf92bb6de6eca7e10f8",
"name": "Jeremy",
"owner": {
"_id": "614323ed282bfd3e68bbaf4f",
"name": "Paul Bettany",
"email": "paul@example.com",
"__v": 0
},
"addressText": "Another street",
"addressNumber": "233",
"zipCode": "09234",
"city": "New York",
"__v": 0
}
]
我的反应组件代码如下所示。
const BarrelDetails = () => {
const { id } = useParams();
const { data: barrel, error, isPending } = useFetch('localhost:8000/api/barrels/' + id);
const history = useHistory();
// const handleClick = () => {
// fetch('http://localhost:8000/api/barrels' + barrel.id, {
// method: 'DELETE'
// }).then(() => {
// history.push('/');
// })
// }
return (
<div className="content">
<div className="barrel-details">
{ isPending && <div>Loading...</div> }
{ error && <div>{ error }</div> }
{ barrel && (
<div>
<h2>{ barrel.title }</h2>
<p>Ansprechpartner { barrel.owner }</p>
<p>Standort: { barrel.city }</p>
<Bookbarrel />
</div>
)}
</div>
</div>
);
}
export default BarrelDetails;
它显示了 bucket.owner id,但没有别的。
我也有问题,我无法再访问主列表中的数据...
我正在使用 useEffect 钩子,并将数据向下传递到列表,但这不再起作用。
useEffect(() => {
fetch('https://devsauna.de/api/barrels/')
// fetch('http://localhost:8000/api/barrels')
.then(res => {
if (!res.ok) {
throw Error('Could not fetch the data for that resource');
}
return res.json();
})
.then(data => {
setBarrels(data);
setError(null);
setIsPending(false);
})
.catch(err => {
setIsPending(false);
setError(err.message);
});
}, []);
我收到错误Error: Objects are not valid as a React child (found: object with keys {_id, name, email, __v}). If you meant to render a collection of children, use an array instead.
Error: Objects are not valid as a React child (found: object with keys {_id, name, email, __v}). If you meant to render a collection of children, use an array instead.
您的数据是一组对象,因此您需要对其进行映射。
barrel && barrel.map(item => {
return <div>
<h2>{ item.title }</h2>
<p>Ansprechpartner { item.owner }</p>
<p>Standort: { item.city }</p>
<Bookbarrel />
</div>
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.