亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在reactjs中設置timeinterval的問題

在reactjs中設置timeinterval的問題

蠱毒傳說 2021-04-27 17:14:20
我嘗試每隔5秒在設置的時間間隔內調用一個函數,但在TypeError中拋出錯誤:this.intialState不是一個函數componentDidMount() {         this.intialState();         setInterval(this.changeSelection,5000);     }    changeSelection(){         this.intialState();     }  TypeError: this.intialState is not a function
查看完整描述

3 回答

?
慕后森

TA貢獻1802條經驗 獲得超5個贊

this在函數中失去其上下文。您可以changeSelection在構造函數中進行綁定


constructor() {

  super();

  this.changeSelection = this.changeSelection.bind(this);

  setInterval(this.changeSelection, 500);

}

或使其成為粗箭頭函數,因為這些函數沒有自己的this上下文,并且會采用父函數的上下文


changeSelection = () => {

  // code here

}


查看完整回答
反對 回復 2021-05-13
?
哈士奇WWW

TA貢獻1799條經驗 獲得超6個贊

更新了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;


查看完整回答
反對 回復 2021-05-13
?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

的arrow函數表達式是語法上緊湊的替代常規的函數表達式,雖然沒有其自己的綁定到this


componentDidMount() { 

  this.intialState(); 

  setInterval(this.changeSelection,5000); 

}

changeSelection = () => { 

  this.intialState(); 

}


查看完整回答
反對 回復 2021-05-13
  • 3 回答
  • 0 關注
  • 205 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號