2017-01-28 11 views
0

私は反応が新しく、問題があります。 アプリケーションコンポーネント:私のヘッダーコンポーネントでスロットルの表示/非表示コンポーネントReactJs

class App extends Component { 

    constructor(){ 
     super(); 
     this.state = { 
      showToast:false, 
      toastMessage: "" 
     }; 

     this.handleShowToast = this.handleShowToast.bind(this); 
    }; 

    handleShowToast(message) { 
     this.setState({ showToast: true, toastMessage: message}); 
     setTimeout(function() { 
      if(this.state.showToast){ 
       this.setState({ showToast: false }); 

      }}.bind(this), 2000); 
     }; 


    render() { 
    return (
      <div id="cont"> 
       <Toast showToast={this.state.showToast} messageToast={this.state.toastMessage} /> 
       <Header handleToast={this.handleShowToast}/> 
      </div> 
    ); 
    } 
} 

私はボタンをクリックするとhadleShowToastを実行し、トーストコンポーネントが正しく表示され、それが仕事ですが、私は私のアプリ3要素を持っています私は(今はsetIntervalで作っていますが、動作しません。なぜなら、2番目の時間ボタンをクリックすると、それは直ちに非表示になるからです。setInterval)hideボタンをもう一度クリックしないと2秒後にToastコンポーネントが隠れます。 、私が再びボタンをクリックした場合ヘッダーコンポーネントi woul dリセットタイマ。 どうすればいいですか?

答えて

1

あなたは明確なタイマーにclearTimeoutを使用することができます。

handleShowToast(message) { 
    this.setState({ showToast: true, toastMessage: message}); 
    if (this.timer) { 
     clearTimeout(this.timer) 
    } 
    this.timer = setTimeout(function() { 
     if(this.state.showToast){ 
      this.setState({ showToast: false }); 
     } 
     this.timer = null; 
    }.bind(this), 2000); 
} 
+0

はい!ありがとうございました!私は受け入れます!しかし、私はデバウンス機能とは何かを答えることはできますか? 私は試しましたが、 "undefined" _ ""を返す – LorenzoBerti

+1

私はこれが[lodash.debounce](https://lodash.com/docs#debounce)と推測しています。それを使用するには、ライブラリ(またはアンダースコア)ライブラリを含める必要があります。 – lorefnon