![](/img/trans.png)
[英]ReactJS : useMemo hook fixed my infinite rerender issue instead of useEffect
[英]Reactjs useMemo hook behaviour like componentDidMount
我正在嘗試使用 useMemo 之類的 useEffect 和 componentDidMount 行為,但我的 useMemo 的行為就像 componentWillMount 一樣,並且呈現不可阻擋。
這是代碼:
useMemo(() => {
console.log('rendered');
fetch(`backend url`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
userId: userInf._id,
fields: ['readers', 'followers', 'news', 'podcast', 'video'],
}),
})
.then((res) => res.json())
.then((res) => {
setUserArticles(res.news);
})
.catch((err) => err);
}, [userArticles]);
請問有什么建議嗎?
useMemo
鈎子用於計算和記憶值。 看起來你的鈎子回調實際上正在更新一些state,並且這個 state 或值也在鈎子依賴數組中聲明,在更新和重新渲染之后,將再次運行鈎子回調並更新 Z9ED39E2EA93142EF573E...創建一個無限循環。
如果您只想在組件掛載時發出一次副作用,例如componentDidMount
,則使用帶有空依賴數組的useEffect
。
useEffect(() => {
console.log('rendered');
fetch(`backend url`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
userId: userInf._id,
fields: ['readers', 'followers', 'news', 'podcast', 'video'],
}),
})
.then((res) => res.json())
.then((res) => {
setUserArticles(res.news);
})
.catch((err) => err);
}, []);
如果你想運行一個效果並且只清理一次(在掛載和卸載時),你可以傳遞一個空數組(
[]
)作為第二個參數。 這告訴 React 你的效果不依賴於 props 或 state 的任何值,所以它永遠不需要重新運行。 這不是作為特殊情況處理的——它直接遵循依賴項數組的工作方式。如果傳遞一個空數組(
[]
),則效果內的道具和 state 將始終具有其初始值。 雖然傳遞[]
作為第二個參數更接近於熟悉的componentDidMount
和componentWillUnmount
mental model,但通常有更好的解決方案來避免過於頻繁地重新運行效果。 另外,不要忘記 React 會延遲運行useEffect
直到瀏覽器繪制完成,所以做額外的工作不是問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.