我的 useEffect 正在從 web api 獲取資料。我想在主頁上呈現所有帖子,并在有人創建新帖子時再次觸發我的 useEffect。問題是當我依賴 useEffect 時,它開始執行無休止的請求。當我將空陣列作為依賴傳遞時,當有人創建新帖子時,它不會在主頁上呈現,直到我重繪 頁面。我在互聯網上閱讀了很多關于這個問題的資訊,但我仍然不知道該怎么做。謝謝
function App() {
const [posts, setPosts] = useState([]);
useEffect(() => {
const jwt = localStorage.getItem("jwt");
fetch('https://localhost:44366/api/Posts/getAllPosts',
{
method: "GET",
headers: {
"Content-Type": "application/json",
'Authorization': 'Bearer ' jwt
},
})
.then(r => r.json()).then(result => setPosts(result));
}, [posts]);
return (
<div >
<Router>
<Header />
<main className="App">
{
posts.map(post => (
<Post keyToAppend={post.CreatedOn} username={post.User.FirstName} title={post.Title} content={post.Content} images={post.ImageUrls} avatarImage={post.User.MainImageUrl} />
))
}
</main>
</Router>
<Footer />
</div>
);
}
帖子組件:
const Post = ({ keyToAppend, username, title, content, images, avatarImage }) => {
return (
<div className="post" key={keyToAppend}>
<div className="post__header">
<Avatar
className="post__avatar"
alt="avatar"
src={avatarImage}
/>
<h3 className="username">{username}</h3>
</div>
<h1 className="title">{title}</h1>
<p className="content">{content}</p>
<p>
{typeof images != "undefined" ? <ImageSlider slides={images} /> : ""}
</p>
</div>
)
}
export default Post;
uj5u.com熱心網友回復:
posts從依賴陣列中洗掉,所以它只是[]. 這將在組件加載時運行一次效果。
useEffect(() => {
const jwt = localStorage.getItem("jwt");
fetch('https://localhost:44366/api/Posts/getAllPosts',
{
method: "GET",
headers: {
"Content-Type": "application/json",
'Authorization': 'Bearer ' jwt
},
})
.then(r => r.json()).then(result => setPosts(result));
}, []);
// ^^????? remove `posts` here
它與您當前的代碼無休止地運行的原因是您的效果回呼更改了posts狀態成員,這會再次觸發效果(因為posts在依賴陣列中)。您只需要在您在效果回呼中讀取的依賴項陣列中包含內容。你從來沒有讀過posts效果回呼。
旁注:該代碼正在fetch成為我在此處描述的API 手槍的犧牲品。您需要r.ok在呼叫之前檢查r.json(并處理錯誤):
useEffect(() => {
const jwt = localStorage.getItem("jwt");
fetch("https://localhost:44366/api/Posts/getAllPosts", {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " jwt
},
})
.then(r => {
if (!r.ok) { // <=================
throw new Error(`HTTP error ${r.status}`);
}
return r.json();
})
.then(result => setPosts(result))
.catch(error => {
// ...handle/report error here...
});
}, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/365790.html
標籤:javascript 反应
