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();
}
添加回答
举报