我試圖從我的 API 中顯示作者串列,我已經創建了簡單的組件,并且正在使用axios. 我的 API 看起來像這樣:
{
"links": [
{
"rel": "self",
"href": "http://localhost:8080/booker/api/authors"
}
],
"content": [
{
"authorId": 4,
"firstName": "Tonyslav",
"lastName": "Shamal",
"webPage": "www.tonisha.gov",
"dateCreated": "2021-12-15T11:58:28.829 00:00",
"numberOfBooks": 13,
"links": [
{
"rel": "books",
"href": "http://localhost:8080/booker/api/books/author/4"
}
]
},
{
"authorId": 6,
"firstName": "Georgio",
"lastName": "Martinez",
"webPage": "www.got.gov",
"dateCreated": "2021-12-15T11:58:28.829 00:00",
"numberOfBooks": 16,
"links": [
{
"rel": "books",
"href": "http://localhost:8080/booker/api/books/author/6"
}
]
}
}
我的 React 組件如下所示:
import { useEffect, useState } from 'react';
import axios from 'axios';
const Authors = () => {
const [authors, setAuthors] = useState([]);
useEffect(() => {
axios.get('http://localhost:8080/booker/api/authors')
.then(res => {
setAuthors(res.data);
})
.catch(err => console.log(err));
}, []);
return (
<div>
{authors.map(author => (
<div className="card" key={author.content.authorId}>
{author.content.firstName}
</div>
))}
</div>
);
}
export default Authors;
這是我在控制臺中的錯誤
TypeError: authors.map is not a function
任何人都可以嘗試幫助我解決此問題,我無法解決此錯誤。
uj5u.com熱心網友回復:
回應是一個物件,而不是陣列,因此您無法對其進行映射。你可能想要更接近這個的東西:
.then(res => {
setAuthors(res.data.content);
})
假設您想遍歷該陣列。然后渲染看起來像這樣:
<div>
{authors.map(author => (
<div className="card" key={author.authorId}>
{author.firstName}
</div>
))}
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/381595.html
標籤:javascript 反应 公理
