2016-10-27 4 views
0

サイズ変更するたびにページの幅を追跡する必要があるコンポーネントを作成しています。しかし、私はそれを行うことができますが、反応は私にエラーを投げつけ続ける。setState()の呼び出しが頻繁に頻繁に行われるため、マウントまたはマウントされたコンポーネントの反復スローエラーが発生する可能性があります。

これはスローエラーである:

warning.js:36 Warning: setState(...): Can only update a mounted or mounting component. 
This usually means you called setState() on an unmounted component. This is a no-op. 
Please check the code for the Nav component. 

エラーの原因となっていると、スタック・トレース・ポイントコードはNavコンポーネント上handleResize()方法です。ちょっとした検索やグーグルを行った後、コンポーネントがマウントされる前にsetState()が呼び出されているということがわかった。イベントリスナーがcomponentDidMount()に登録されているため、これは奇妙です。記事はcomponentWillMountを使用して示唆された葉巻はありません。なぜこれが起こっているのか正確にはわかりません。このような速いペースでリサイズの量が増えているのかもしれません。

handleResize() { 
    this.setState((prevState, currProps) => ({ 
     height: window.innerHeight, 
     width: window.innerWidth 
    })); 
    if (this.props.showMenu === undefined) { 
     if (this.state.width > (this.props.breakPoint || 767) && this.state.showMenu) { 
     this.setState((prevState, currProps) => ({ 
      showMenu: false, 
     })); 
     } 
    } else { 
     if (this.state.width > (this.props.breakPoint || 767) && this.props.showMenu) { 
     this.props.closeMenu(); 
     } 
    } 
    } 

    componentDidMount() { 
    window.addEventListener('resize', this.handleResize.bind(this)); 
    } 

    componentWillUnmount() { 
    window.removeEventListener('resize', this.handleResize.bind(this)) 
    } 
+0

あなたは 'handleResizeをバインドしています。 () 'もあなたのコンストラクタで? 'this.handleResize()= this.handleRezise.bind(this);'。また、 'componentDidMount()'の代わりに 'componentWillMount()'を使ってはいけませんか?私はこれを二重にチェックする必要があります。また、これは非同期ですが、コンポーネントのマウント後に関数を移動するのに役立ちます。 – Dandy

+0

'Nav 'の完全なコードを投稿する方がよい。 –

答えて

1

this.handleResive.bind(this)window.removeEventListener('resize', this.handleResize.bind(this))も新しい機能を作成し、あなたが最初の場所で追加したのと同じ機能を渡していないことを意味新しい関数を作成します。これは、バインドして以前に追加したものが削除されていないことを意味します。(全く同じように動作しますが)と同じ機能ではないためです。これを解決する

一つの方法は、それを追加する前に機能を格納することです:

componentDidMount() { 
    const resizeHandler = this.handleResize.bind(this); 
    this.setState({resizeHandler}); 
    window.addEventListener('resize', resizeHandler); 
} 

componentWillUnmount() { 
    window.removeEventListener('resize', this.state.resizeHandler); 
    //you could cleanup state here but it's not necessary 
} 

誰でも機能をイベント処理を保存するためのより良い方法を持っている場合はチャイムください

関連する問題