2016-07-25 6 views
5

に反応:InfiniteScrolling経由でラップされているコンポーネントをアンマウントした後はアンマウントし上のイベントリスナーを削除私は高次の成分は次のように反応していた

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; 
} 

(私はスクロールなかったとき)、彼らはまだのようなエラーを投げるところ:

警告:setState(...):取り付け済みまたは取り付け済みの コンポーネントのみを更新できます。これは通常、アンマウントされた コンポーネントに対してsetState()を呼び出したことを意味します。これはノーオペレーションです。定義されていない コンポーネントのコードを確認してください。

コンポーネントのアンマウントでscrollイベントを削除しましたが、それはうまくいかなかった。

しかし、私はこれを好きにコードを変更する場合:

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

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

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

すべてが問題なく、正常に動作しているようです。

私はそれらがまったく同じものだと感じますが、最初のものが前に述べたようにコンソールにエラーを投げていた間、2番目のものはうまく動作します!

答えて

20

あなたはいつも

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、そう単純なミスは、新しい関数を作成しています! 'bind'は新しい関数を作成します。私の悪い! –

関連する問題