reactjs / reactjs/react.dev

A note about not firing side effects in useState(prev => next) ?

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

So I ended up doing this by mistake after a wonky merge:

let Foo = (props) => {
    let [bar, setBar] = useState();
    
    let handleClick = () => {
        useState(bar => {
            let newBar = bar + 1;
            props.handleBarChange(newBar); // bad, which isn't surprising
            return newBar;
        });
    };

    return <div onClick={handleClick}>click me</div>;
};

If you fire a side effect such as calling something that sets state in a higher component from a useState updater function, you get the error "Cannot update a component from inside the function body of a different component" (but not always! It seems to depend on internal timing). This definitely seems like a bad idea when you look at it, but I couldn't find any mention in the docs that this is bad.

https://reactjs.org/docs/hooks-reference.html#functional-updates

There is the note about side effects generally on useEffect:

Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase)

But this is not in the main body of a function component, doesn't feel like a true side effect as it's still just setting state within React, and doesn't feel like it's in the render phase either.

I initially wanted to comment about this here (https://github.com/facebook/react/issues/18178), because the general message of that thread was "don't set state of another component in a render method", and I've managed to get this error message without doing that, but the thread is locked. Thanks.

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 trang tham khảo Hooks được liên kết, đặc biệt là phần cập nhật theo hàm, và so sánh hướng dẫn trong đó với ghi chú được trích dẫn về side effect của useEffect. Làm rõ liệu các side effect bên trong updater của useState có không được hỗ trợ hay không và giải thích hành vi liên quan; được xem là hoàn thành khi tài liệu đề cập đến ví dụ này mà không có sự mơ hồ.

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
Khá 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.