React docs on useEffect
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- JavaScript
- Star
- 11.8k
- Fork
- 7.9k
- Merge trung bình
- 1 ngày 11 giờ
- Pull request đã merge (30 ngày)
- 11
Mô tả
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';
}
Hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Hướng nghiên cứu
Bắt đầu với ví dụ useEffect trong tài liệu được liên kết và xem lại trình tự subscription, cleanup và setIsOnline được mô tả. Làm rõ liệu ví dụ có cần giải thích về hành vi rerender hay cần một ví dụ được sửa đổi, sau đó cập nhật tài liệu để vòng đời effect dự kiến và các tiêu chí hoàn thành được nêu rõ.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Đánh giá
- Công nghệ
- javascript, react
- Lĩnh vực
- documentation
- Loại issue
- Tài liệu
- Độ khó
- 3/5
- Thời gian dự kiến
- 1-2 ngày
- Mức độ hoạt động
- Đình trệ
- Độ rõ ràng
- Cần làm rõ
- Mức phù hợp với người mới
- 35/100