使用babel进行编译时出现ESLint错误:
任何想法如何摆脱这些同时使我的计时器仍然按预期工作?或者你有更好的方式让我做我的计时器?
class RequestTimer extends Component {
constructor(props) {
super(props);
this.state = {
seconds: 0,
minutes: 0,
hours: 0
}
this.getTime = this.getTime.bind(this);
}
getTime() {
let second = this.state.seconds
let minute = this.state.minutes;
let hour = this.state.hours;
this.state.seconds % 59 === 0 && this.state.seconds !== 0 ? minute += 1:null;
this.state.minutes % 59 === 0 && this.state.seconds % 59 === 0 && this.state.minutes !== 0 ? (hour += 1, minute = 0):null;
this.setState({
seconds: second +=1,
minutes: minute,
hours: hour
})
}
componentDidMount() {
this.timer = setInterval(this.getTime, 1000)
}
render() {
return (
<TimerContainer>
<h2>Last Request:</h2>
<p>{this.state.hours}h {this.state.minutes}m {this.state.seconds % 60}s</p>
</TimerContainer>
)
}
}
您想使用正确的if
声明:
getTime() {
let second = this.state.seconds
let minute = this.state.minutes;
let hour = this.state.hours;
if (this.state.seconds % 59 === 0 && this.state.seconds !== 0) {
minute += 1;
}
if (this.state.minutes % 59 === 0 && this.state.seconds % 59 === 0 && this.state.minutes !== 0) {
hour += 1;
minute = 0;
}
this.setState({
seconds: second +=1,
minutes: minute,
hours: hour
});
}
如果您不想对结果值执行任何操作,请不要使用三元运算符。尤其是当你没有else
的情况下或者你必须使用逗号运算符来做多件事时你不应该使用它。
有几种解决方案。
1.)只需使用文件顶部的eslint-disable禁用整个文件的规则。
/* eslint-disable no-unused-expressions */
2.)你应该在所有行(28,29)的末尾写下面的代码,所以它被禁用了。
/* eslint-disable-line */
或者,修改三元操作以具有L.H.S表达
this.state.seconds % 59 === 0 && this.state.seconds !== 0 ? minute += 1:null;
改变
minute = this.state.seconds % 59 === 0 && this.state.seconds !== 0 ? minute + 1:null;