我试图使用setInterval
调用reactjs中的函数,如下所示:
import React,{Component} from 'react';
class Timer extends Component {
trigger(){
this.clock = this.setState({clock:Date.now()-this.props.date});
}
setInterval(this.trigger,1000);
constructor(props){
super(props);
this.state = {
clock:0
};
this.trigger = this.trigger.bind(this);
}
render(){
this.state.clock=Math.round(this.state.clock/1000);
return(
<div>
<p>You are here since</p>
<span>{this.state.clock}</span>
<p>Seconds.</p>
<button onClick={this.trigger}>Click me</button>
</div>
);
}
}
export default Timer;
而是返回此错误:
Syntax error: F:/reactjs1/project-6/timer/src/Timer.js: Unexpected token (8:22)
Syntax error: F:/reactjs1/project-6/timer/src/Timer.js: Unexpected token (8:22)
6 | this.clock = this.setState({clock:Date.now()-this.props.date});
7 | }
> 8 | setInterval(trigger,1000);
^
答案 0 :(得分:2)
试试这个:
trigger() {
let newTime = Date.now() - this.props.date;
setInterval(() => {
this.setState({
clock: newTime;
})
}, 1000);
}
您可以通过多种方式执行此功能,最佳选项可能位于组件或容器的componentDidMount()中。然后每秒运行一次,每次都更新this.clock的值。