在react中访问嵌套JSON API对象中的数据



我在JSON-Api中有这个数据,但是我的react应用程序不希望从嵌套的对象中获取值。

[
{
"_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
}
]

react组件的代码是这样的:


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;

显示桶。所有者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.

你的数据是一个对象数组,所以你需要映射它。

barrel && barrel.map(item => {
return <div>
<h2>{ item.title }</h2>
<p>Ansprechpartner { item.owner }</p>
<p>Standort: { item.city }</p>
<Bookbarrel />
</div>
})

最新更新