Javascript reactjs中设置时间间隔的问题

Javascript reactjs中设置时间间隔的问题,javascript,reactjs,Javascript,Reactjs,我试图每隔5秒在设置的时间间隔内调用一个函数,但我抛出了错误 TypeError:this.intialState不是函数 componentDidMount() { this.intialState(); setInterval(this.changeSelection,5000); } changeSelection(){ this.intialState(); } TypeError: this.int

我试图每隔5秒在设置的时间间隔内调用一个函数,但我抛出了错误 TypeError:this.intialState不是函数

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

  TypeError: this.intialState is not a function
arrow函数表达式是正则函数表达式的一种语法紧凑的替代方法,尽管它没有自己的绑定

组件安装{ 这是初始状态; setIntervalthis.changeSelection,5000; } changeSelection==>{ 这是初始状态; } 这会丢失函数中的上下文。您可以在构造函数中绑定changeSelection

constructor() {
  super();
  this.changeSelection = this.changeSelection.bind(this);
  setInterval(this.changeSelection, 500);
}
或者让它成为一个胖箭头函数,因为这些函数没有自己的上下文,并且将接受父函数的上下文

changeSelection = () => {
  // code here
}

问题是您的函数“changeSelection”无权访问“this”

有两种简单的方法可以解决此问题:

在“构造函数”中,添加此行以将“this”与changeSelection绑定 this.changeSelection=this.changeSelection.bind

箭头函数 changeSelection==>{}


您可以阅读更多关于为什么需要绑定的信息

使用类时钟扩展组件更新5秒倒计时

在哪里声明了initialState方法?的可能重复项
    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;