想法:我想在登录后显示时间,并在注销后隐藏它。程序运行正常,但注销后我收到警告(如图3所示)。所以,我想知道:警告是否会影响应用程序,如果是,如何解决这个问题<这是钟。jsx:
import React from 'react'
export class Clock extends React.Component {
constructor(props) {
super(props)
this.state = {
date: new Date()
}
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
)
}
componentWillMount() {
clearInterval(this.timerID)
}
tick() {
this.setState({
date: new Date()
})
}
render() {
return (
<div>
<hr />
<p>Current Time: </p>
<p>{this.state.date.toLocaleTimeString()}.</p>
<hr />
</div>
)
}
}
在索引中调用该组件。jsx:
function Logout(props) {
return (
<div>
<button className="btn btn-danger" onClick={props.onClick}>
Logout
</button>
<Clock />
</div>
)
}
尝试在componentWillUnmount中调用clearInterval。这确保了当您的时钟组件在DOM中不可用时,不会调用写在tick中的setState方法。
在钟里。jsx I输入componentWillMount()而不是componentWillUnmount()时出错
旧代码片段:
componentWillMount() {
clearInterval(this.timerID)
}
固定:
componentWillUnmount() {
clearInterval(this.timerID)
}