[英]React useEffect does infinite loop
我的 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;
從依賴數組中刪除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
state 成員,這再次觸發了效果(因為posts
在依賴項數組中)。 您只需要在效果回調中讀取的依賴數組中包含內容。 您從不閱讀效果回調中的posts
。
旁注:該代碼正在成為我 在此處描述的fetch
API footgun 的犧牲品。 您需要在調用r.json
r.ok
並處理錯誤):
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...
});
}, []);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.