1 回答

TA貢獻1770條經驗 獲得超3個贊
您始終可以在渲染之前進行檢查并渲染后備加載指示器..
return (
post ?
<div className={"section"}>
<div className={"container"}>
<div className={"first-post"}>
<div className={"first-post-title"}>
<h2>
{post.title.length > 20
? post.title.slice(0, 85) + " ..."
: post.title}
</h2>
</div>
</div>
</div>
</div>
: "loading..."
)
上面的代碼僅在定義后才加載 post,否則返回“loading”。
在useEffect鉤子內部,您可以調用 API 并設置狀態。
useEffect(() => {
fetch("URL")
.then(response => response.json())
.then(json => setPost(json));
}, [])
API 調用完成后,狀態會發生變化,并且組件會使用發布數據重新呈現。
一個例子https://stackblitz.com/edit/react-htofev
添加回答
舉報