ReactアプリのsetInterval 質問する

ReactアプリのsetInterval 質問する

私はまだ React を使い始めたばかりですが、ゆっくりと取り組んでいて、行き詰まっていることに遭遇しました。

React で「タイマー」コンポーネントを構築しようとしていますが、正直言って、これを正しく (または効率的に) 実行しているかどうかわかりません。以下のコードでは、オブジェクトを返すように状態を設定し、、、{ currentCount: 10 }を試していますが、10 から 9 まで「カウントダウン」する状態しか得られません。componentDidMountcomponentWillUnmountrender

componentDidMount2 つの部分からなる質問です。何が間違っているのでしょうか? また、( &を使用するのではなく) setTimeout を使用するより効率的な方法はありますかcomponentWillUnmount?

よろしくお願いします。

import React from 'react';

var Clock = React.createClass({

  getInitialState: function() {
    return { currentCount: 10 };
  },

  componentDidMount: function() {
    this.countdown = setInterval(this.timer, 1000);
  },

  componentWillUnmount: function() {
    clearInterval(this.countdown);
  },

  timer: function() {
    this.setState({ currentCount: 10 });
  },

  render: function() {
    var displayCount = this.state.currentCount--;
    return (
      <section>
        {displayCount}
      </section>
    );
  }

});

module.exports = Clock;

ベストアンサー1

コードに 4 つの問題があることがわかりました:

  • タイマーメソッドでは、現在のカウントを常に10に設定しています
  • レンダリングメソッドで状態を更新しようとする
  • setState実際に状態を変更するためにメソッドを使用することはありません
  • 状態にintervalIdを保存していません

これを修正してみましょう:

componentDidMount: function() {
   var intervalId = setInterval(this.timer, 1000);
   // store intervalId in the state so it can be accessed later:
   this.setState({intervalId: intervalId});
},

componentWillUnmount: function() {
   // use intervalId from the state to clear the interval
   clearInterval(this.state.intervalId);
},

timer: function() {
   // setState method is used to update the state
   this.setState({ currentCount: this.state.currentCount -1 });
},

render: function() {
    // You do not need to decrease the value here
    return (
      <section>
       {this.state.currentCount}
      </section>
    );
}

これにより、タイマーは 10 から -N まで減少します。0 まで減少するタイマーが必要な場合は、少し変更したバージョンを使用できます。

timer: function() {
   var newCount = this.state.currentCount - 1;
   if(newCount >= 0) { 
       this.setState({ currentCount: newCount });
   } else {
       clearInterval(this.state.intervalId);
   }
},

おすすめ記事