reactjs / reactjs/react.dev

setState() callback function: potential confusion of call order

Đang mở
#691 0 bình luận 2 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ả

This paragraph from the React.Component reference page:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.

can create the impression that instead of doing:

this.setState({ value: 5 });
console.log(this.state.value); // => not necessarily 5

you can use the callback function to safely read the state back:

this.setState({ value: 5 }, () => console.log(this.state.value)); // => "guaranteed" 5

(especially if you draw a parallel between the callback function and the updater function)

and it may actually work in some cases where there's no setState batching, but as more calls get batched in the future, these constructs may generate unintended side-effects.

Instead, we could clarify that all callback functions for a batch of setState() calls get called after the entire batch has been processed.

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 phần setState của trang tham chiếu React.Component được liên kết trong issue. Xem lại cách diễn đạt về callbacks và batching, sau đó cập nhật để thời điểm callback được thực thi và state có sẵn sau một batch trở nên rõ ràng; được xem là hoàn tất khi các ví dụ không thể khiến người đọc hiểu rằng một callback chỉ quan sát bản cập nhật riêng lẻ của nó.

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ó
2/5
Thời gian dự kiến
1-3 giờ
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Đặc tả rõ ràng
Mức phù hợp với người mới
45/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.