2016-07-25 16 views
5

tôi đã thành phần bậc cao trong phản ứng như thế này:Remove Event Listener Mở Ngắt kết nối bộ Phản ứng

export default function (InnerComponent) { 
    class InfiniteScrolling extends React.Component { 

     constructor(props){ 
      super(props); 
     } 

     componentDidMount() { 
      window.addEventListener('scroll', this.onScroll.bind(this), false); 
     } 

     componentWillUnmount() { 
      window.removeEventListener('scroll', this.onScroll.bind(this), false); 
     } 

     onScroll() { 
      if ((window.innerHeight + window.scrollY) >= (document.body.offsetHeight - 50)) { 
       const { scrollFunc } = this.props; 
       scrollFunc(); 
      } 
     } 

     render() { 
      return <InnerComponent {...this.props} />; 
     } 
    } 

    InfiniteScrolling.propTypes = { 
     scrollFunc: PropTypes.func.isRequired 
    }; 

    return InfiniteScrolling; 
} 

Sau unmount toàn bộ các thành phần trong đó có được quấn qua InfiniteScrolling, họ nơi vẫn ném lỗi tương tự (khi tôi đã di chuyển) :

Cảnh báo: setState (...): Chỉ có thể cập nhật thành phần gắn kết hoặc gắn . Điều này thường có nghĩa là bạn đã gọi setState() trên thành phần chưa được kết nối . Đây là một no-op. Vui lòng kiểm tra mã cho thành phần chưa được xác định .

Mặc dù tôi đã xóa sự kiện scroll khi tháo thành phần của mình. Nó không hoạt động.

Nhưng khi tôi đã thay đổi mã như thế này:

constructor(props){ 
    super(props); 
    this.onScroll = this.onScroll.bind(this); 
} 

componentDidMount() { 
    window.addEventListener('scroll', this.onScroll, false); 
} 

componentWillUnmount() { 
    window.removeEventListener('scroll', this.onScroll, false); 
} 

tất cả mọi thứ dường như được làm việc tốt, mà không cần bất kỳ vấn đề.

Tôi cảm thấy chúng chính xác giống nhau, nhưng điều thứ hai hoạt động tốt trong khi đầu tiên là ném lỗi trong bảng điều khiển như đã đề cập trước đó!

Trả lời

20

Bạn luôn tạo ra chức năng mới

constructor(props){ 
     super(props); 
     this.onScroll = this.onScroll.bind(this); //bind function once 
    } 

    componentDidMount() { 
     window.addEventListener('scroll', this.onScroll, false); 
    } 

    componentWillUnmount() { 
     // you need to unbind the same listener that was binded. 
     window.removeEventListener('scroll', this.onScroll, false); 
    } 
+0

OMG, đơn giản như vậy sai lầm !! 'bind' tạo ra một hàm mới. Lỗi của tôi! –

Các vấn đề liên quan