嘿,我已经写了一个网站,要在该网站上显示currentTime + 36分钟,并显示一个计时器,直到那时。
由于在newDate之后在“ $”或“ +”位置出现以下错误,我的代码无法编译:
分析错误:意外的令牌,预期为“ {”
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
const styles = theme => ({
whiteFont: {
color: 'white',
textAlign: 'center'
}
});
class TimeCount extends Component {
constructor(props) {
super(props);
this.state = {
timerOn: false
};
this.timerStart = this.timerStart.bind(this);
this.timerStop = this.timerStop.bind(this);
this.tick = this.tick.bind(this);
this.currentTime = this.currentTime.bind(this);
this.minutesPlus36 = this.minutesPlus36.bind(this);
this.hoursPlus36 = this.hoursPlus36.bind(this);
this.counterMinutes = 36;
// this.currentTime = 45;
this.counterSeconds = 0;
this.counterStep = 1;
this.classes = props.classes;
}
timerStart() {
this.timerID = setInterval(() => this.tick(), 1000);
this.setState({ timerOn: true });
}
currentTime() {
var today = new Date();
var date;
var hours = today.getHours();
var minutes = today.getMinutes();
var text= ":"
var newDate={hoursPlus36(hours, minutes) ${text} + minutesPlus36(minutes)};
// var newDate={hoursPlus36(hours, minutes) + ":"+ minutesPlus36(minutes)};
this.setState({currentTime: newDate});
}
minutesPlus36(minutes) {
return (minutes + 36) % 60;
}
hoursPlus36(hours, minutes) {
if (minutes + 36 > 59) return hours + 1;
else return hours;
}
timerStop() {
clearInterval(this.timerID);
this.setState({ timerOn: false });
}
tick() {
if (this.counterSeconds == 0) {
this.counterMinutes = this.counterMinutes - this.counterStep;
this.counterSeconds = 59;
this.setState({
counterMinutes: this.counterMinutes,
counterSeconds: this.counterSeconds
});
} else {
this.counterSeconds = this.counterSeconds - this.counterStep;
this.setState({
counterSeconds: this.counterSeconds
});
}
if (this.counterMinutes <= 0 && this.counterSeconds <= 0) {
this.setState({ timerOn: false });
this.timerStop();
} else {
this.setState({ timerOn: true });
}
console.log('counterMinutes: ' + this.counterMinutes);
}
componentDidMount() {
let timerOn = this.state.timerOn;
this.timerStart();
this.currentTime();
//this.setState({currentTime: {currentTime()}});
}
render() {
return (
<React.Fragment>
<span>
<span className={this.classes.whiteFont}>
The emergency team arrives at {this.state.arrivalTime} pm.
</span>
<br />
Time until rescue team arrival: {this.state.counterMinutes} minutes
</span>
</React.Fragment>
);
}
}
export default withStyles(styles)(TimeCount);
非常感谢您的帮助。谢谢!
编辑:我根据建议更改了代码并编辑了新错误
答案 0 :(得分:0)
您正在用构造函数编写this.currentTime=45
,并且从未使用过。
另外,您正在尝试在this.currentTime()
中调用componentDidMount()
,这不是函数,因为您在构造函数中为this.currentTime
分配了一个值。
要使其正常工作,
将this.currentTime=45
从构造器中删除,因为它们没有用。
您还错过了将this
绑定到currentTime
函数,将其添加到构造函数中的情况,
this.currentTime = this.currentTime.bind(this);
更新
检查是否可行
var text = ':';
var hoursPlus = this.hoursPlus36(hours, minutes);
var minutesPlus = this.minutesPlus36(minutes);
var newDate = hoursPlus + text + minutesPlus;
this.setState({currentTime: newDate});