首页 > 解决方案 > reactjs中设置时间间隔的问题

问题描述

我试图每隔 5 秒在设定的时间间隔内调用一个函数,但我在 TypeError 中抛出错误:this.intialState is not a function

componentDidMount() { 
        this.intialState(); 
        setInterval(this.changeSelection,5000); 
    }
    changeSelection(){ 
        this.intialState(); 
    }

  TypeError: this.intialState is not a function

标签: javascriptreactjs

解决方案


使用更新的 5 秒倒计时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>
        );
      }
    }

   export default Clock;

推荐阅读