Countdown timer in React

后端 未结 7 831
甜味超标
甜味超标 2020-11-30 00:05

I have seen lots of countdown timers in JavaScript and wanted to get one working in React.

I have borrowed this function I found online:

secondsToTim         


        
7条回答
  •  没有蜡笔的小新
    2020-11-30 00:27

    The problem is in your "this" value. Timer function cannot access the "state" prop because run in a different context. I suggest you to do something like this:

    ...
    startTimer = () => {
      let interval = setInterval(this.timer.bind(this), 1000);
      this.setState({ interval });
    };
    

    As you can see I've added a "bind" method to your timer function. This allows the timer, when called, to access the same "this" of your react component (This is the primary problem/improvement when working with javascript in general).

    Another option is to use another arrow function:

    startTimer = () => {
      let interval = setInterval(() => this.timer(), 1000);
      this.setState({ interval });
    };
    

提交回复
热议问题