Reactでカウントタイマー機能を作る①
【目標】
Reactでカウントタイマー機能を作る
【困ったこと】
以下の通りコードを書いたのだが、npm startでブラウザ表示しようとしたところ、エラーになってしまった。
import React, {Component} from 'react'; class Timer extends Component{ constructor(props){ super(props); this.state={ remainMSec:1500000, //初期の残り時間は25分 remainM:this.remainMSec.getMinutes(), //ミリ秒を「分」の形で取得する remainS:this.remainMSec.getSeconds(), //ミリ秒を「秒」の形で取得する label:`${this.remainM}:${this.remainS}` }; this.oldTime=Date.now(); //oldTimeでスクリプト開始時の時間を記録する this.doCountdown = this.doCountdown.bind(this);A } timerStyle = { fontSize: '40px', color: 'hsl(213,100%,69%)' } btnStyle = { fontSize: '20px', padding: '10px', backgroundColor:'hsl(213,100%,69%)', borderRadius: '10px' } doCountdown(){ const timerId = setInterval(()=>{ /* setInterval内でDate.now()を実行することで、1秒ごとに更新される現在の時間をcurrentTImeという名称で取得することができる。*/ const currentTime=Date.now(); //差分を求める const diff=currentTime-this.state.oldTime; //残りのミリ秒を計算し、remainSecを更新 this.setState((state)=>({ remainMSec:state.remainMSec-diff })); if(this.state.remainMSec <=0){ //カウントダウンを終了する。 clearInterval(timerId); this.setState((state)=>({ label:'Time Up!!' })); } },1000); } render(){ return <div> <p style={this.timerStyle} onClick={this.doCountdown()}>{this.state.label}</p> <p style={this.btnStyle}>スタート</p> </div> }; } export default Timer;
【問題の切り出し】
画像の通り「TypeError: Cannot read property 'getMinutes' of undefined」というエラー表示が出ていた。
おそらく「remainMSec:1500000」の部分で、stateの初期値としてDateオブジェクトではなく、数値を設定していたことに問題が
あるのではないか?
↓
remainMSecの定義を考え直すことから修正しようと思う。