3 回答
TA貢獻1802條經驗 獲得超5個贊
this在函數中失去其上下文。您可以changeSelection在構造函數中進行綁定
constructor() {
super();
this.changeSelection = this.changeSelection.bind(this);
setInterval(this.changeSelection, 500);
}
或使其成為粗箭頭函數,因為這些函數沒有自己的this上下文,并且會采用父函數的上下文
changeSelection = () => {
// code here
}
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;
TA貢獻1875條經驗 獲得超3個贊
的arrow函數表達式是語法上緊湊的替代常規的函數表達式,雖然沒有其自己的綁定到this
componentDidMount() {
this.intialState();
setInterval(this.changeSelection,5000);
}
changeSelection = () => {
this.intialState();
}
添加回答
舉報
