React docs on useEffect
還沒有人認領這個 Issue。
- 主要語言
- JavaScript
- 星號
- 11.8k
- 分支
- 7.9k
- 平均合併
- 1 天 11 小時
- 30 天內合併 PR
- 11
描述
The docs have an example about using useEffect with cleanup, here.
If I carry out the sequence, then I would get
run effect -> subscribe to update from ChatApi -> setIsOnline -> cleanup -> run effect -> subscribe to update from ChatApi -> setIsOnline
I am unsure as to why this does not lead to an infinite loop without use of the dependency array?
One understanding / theory that I have is:
The first time the subscription cause setIsOnline(true). Next time (after one cycle of unsubscribe/effect), the setIsOnline gets argument as true and hence further update to the component does not occur. This is assuming that this form of setIsOnline does not re-render if the isOnline has not changed (it is still true).
I am curious as to why the piece of code is correct.
Here it is as copied from the useEffect documentation
import React, { useState, useEffect } from 'react';
function FriendStatus(props) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從連結的 useEffect 文件範例開始,檢視其中描述的 subscription、cleanup 和 setIsOnline 順序。釐清該範例是否需要說明其重新渲染行為,或是否需要修改後的範例,然後更新文件,讓預期的 effect 生命週期與完成標準清楚明確。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- javascript, react
- 領域
- documentation
- Issue 類型
- 文件
- 難度
- 3/5
- 預估耗時
- 1-2 天
- 活躍度
- 停滯
- 描述清晰度
- 需要釐清
- 新手友好度
- 35/100