在reactjs中设置timeinterval的问题

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


componentDidMount() { 

        this.intialState(); 

        setInterval(this.changeSelection,5000); 

    }

    changeSelection(){ 

        this.intialState(); 

    }


  TypeError: this.intialState is not a function


蛊毒传说
浏览 177回答 3
3回答

慕后森

this在函数中失去其上下文。您可以changeSelection在构造函数中进行绑定constructor() {  super();  this.changeSelection = this.changeSelection.bind(this);  setInterval(this.changeSelection, 500);}或使其成为粗箭头函数,因为这些函数没有自己的this上下文,并且会采用父函数的上下文changeSelection = () => {  // code here}

哈士奇WWW

更新了5秒倒计时,使用 class Clock extends Component&nbsp; &nbsp; import React, { Component } from 'react';&nbsp; &nbsp; class Clock extends Component {&nbsp; &nbsp; &nbsp; constructor(props){&nbsp; &nbsp; &nbsp; &nbsp; super(props);&nbsp; &nbsp; &nbsp; &nbsp; this.state = {currentCount: 10}&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; timer() {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currentCount: this.state.currentCount - 1&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; if(this.state.currentCount < 1) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; clearInterval(this.intervalId);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; componentDidMount() {&nbsp; &nbsp; &nbsp; &nbsp; this.intervalId = setInterval(this.timer.bind(this), 1000);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; componentWillUnmount(){&nbsp; &nbsp; &nbsp; &nbsp; clearInterval(this.intervalId);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; &nbsp; return(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>{this.state.currentCount}</div>&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;export default Clock;

翻过高山走不出你

的arrow函数表达式是语法上紧凑的替代常规的函数表达式,虽然没有其自己的绑定到thiscomponentDidMount() {&nbsp;&nbsp; this.intialState();&nbsp;&nbsp; setInterval(this.changeSelection,5000);&nbsp;}changeSelection = () => {&nbsp;&nbsp; this.intialState();&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript