下面是我為從使用 Golang 撰寫的 localhost api 獲取資料而撰寫的內容http://localhost:8081/post,
const HomePost1 = () => {
const [author, setName] = useState('');
const [title, setTitle] = useState('');
useEffect(() => {
(
async () => {
const response = await fetch('http://localhost:8081/post', {
headers: {'Content-Type': 'application/json'},
credentials: 'include',
});
const content = await response.json();
setName(content.author)
setTitle(content.title)
}
)();
});
return (
<div>
{"welcome " author}
{"content:" title}
</div>
)
}
我在網頁上顯示了這個,沒有錯誤訊息:
welcome undefined content:undefined
來自 localhost 的 api 如下所示:
{
messges: [
{
id: 2,
title: "This is second sample post",
author: "DEF"
},
{
id: 3,
title: "This is third sample post",
author: "DEF"
}
]
}
當我從另一個我撰寫的 api 獲取資料并成功顯示結果時,我使用了完全相同的方法。這可能是什么問題?這是由前端還是后端引起的?
uj5u.com熱心網友回復:
您的 api 發送陣列,因此您應該使用 map() 而不是直接呼叫 content.title 這里是作業示例。
const HomePost1 = () => {
const [res, setRes] = useState([]);
useEffect(() => {
(
async () => {
const response = await fetch('http://localhost:8081/post', {
headers: {'Content-Type': 'application/json'},
credentials: 'include',
});
const content = await response.json();
setRes(content.messges)
}
)();
});
return (
<div>
{ res.map((rec, i ) => {
return (<div key={i}>{"welcome " rec.author}
{"content:" rec.title}</div>)
}) }
</div>
)
}
uj5u.com熱心網友回復:
根據 api 結果,回應包含一個陣列。
您可以嘗試在控制臺中列印出變數“content”,以查看物件結構。
我建議你可以嘗試這樣的事情:
content[0].title
// OR
content.messges[0].title
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/459417.html
標籤:javascript 反应 api
