setInterval в приложении React

Я все еще довольно новичок в React, но я медленно продвигаюсь вперед, и я столкнулся с чем-то, на чем я застрял.

Я пытаюсь создать компонент "таймер" в React, и, честно говоря, я не знаю, правильно ли я это делаю (или эффективно). В моем коде ниже я устанавливаю состояние для возврата объекта { currentCount: 10 } и играли с componentDidMount, componentWillUnmount и render и я могу только заставить государство "отсчитывать" от 10 до 9.

двухчастный вопрос: Что я становится неверным? И есть ли более эффективный способ использовать setTimeout (а не использовать componentDidMount & 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;

2 ответов


Я вижу 4 Проблемы с вашим кодом:

  • в методе таймера вы всегда устанавливаете текущее количество до 10
  • вы пытаетесь обновить состояние в методе render
  • вы не используете 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);
   }
},

обновлено 10-секундный обратный отсчет с помощью class Clock extends Component

import React, { Component } from 'react';

class Clock extends Component {
  constructor(props){
    super(props);
    this.state = {currentCount: 10}
  }
  timer() {
    this.setState({
      currentCount: this.state.currentCount - 1
    })
    if(this.state.currentCount < 1) { 
      clearInterval(this.intervalId);
    }
  }
  componentDidMount() {
    this.intervalId = setInterval(this.timer.bind(this), 1000);
  }
  componentWillUnmount(){
    clearInterval(this.intervalId);
  }
  render() {
    return(
      <div>{this.state.currentCount}</div>
    );
  }
}

module.exports = Clock;