reactjs / reactjs/react.dev

Questionable Comment in the `useEvent` Example

Đang mở
#5,280 0 bình luận 1 reaction 0 người được giao Xem trên GitHub

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ả

I found a paragraph from Separating Events from Effects in the beta React Docs, which I couldn't wrap my head around:

In this example, url inside onVisit corresponds to the latest url (which could have already changed), but visitedUrl corresponds to the url that originally caused this Effect (and this onVisit call) to run.

The mentioned example is effectively the one below:

function Page({ url }) {
  const { items } = useContext(ShoppingCartContext);
  const numberOfItems = items.length;

  const onVisit = useEvent(visitedUrl => {
    // `url` captured here is claimed to be the latest, not the original
    // but what about `numberOfItems`?
    logVisit(visitedUrl, numberOfItems);
  });

  // intend to log the `url` that originally caused this Effect, 
  // along with the original `numberOfItems`.
  useEffect(() => {
    setTimeout(() => {
      onVisit(url);
    }, 5000); // Delay logging visits
  }, [url]);

  // ...
}

More essentially, I believe my confusion stems from the claims below:

This solves the problem. Similar to the set functions returned from useState, all Event functions are stable: they never change on a re-render. This is why you can skip them in the dependency list. They are not reactive.

How can Event functions like onVisit are stable, when they need to capture the relevant reactive values like numberOfItems?

Are they stable, but have access to the freshly-constructed anonymous function, which captures the relevant reactive values?

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. 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.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. 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ụ “Separating Events from Effects” được liên kết trong issue và so sánh các nhận định về tính ổn định của useEvent với các giá trị numberOfItems và url được hiển thị. Công việc được xem là hoàn tất khi tài liệu làm rõ callback bị trì hoãn quan sát các giá trị nào và giải thích vì sao có thể bỏ qua hàm sự kiện trong các dependency.

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ó
5/5
Thời gian dự kiến
Hơn một tuần
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
25/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.