想法:我希望在登录后显示时间并在注销后隐藏它。程序有效,但退出后我收到警告(见图3)。所以,我想知道:警告会影响app,如果是的话,如何解决这个问题。
这里是Clock.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>
)
}
}
在index.jsx中调用该组件:
function Logout(props) {
return (
<div>
<button className="btn btn-danger" onClick={props.onClick}>
Logout
</button>
<Clock />
</div>
)
}
答案 0 :(得分:0)
尝试在componentWillUnmount中调用clearInterval。这可以确保当您的Clock组件在DOM中不可用时,不会调用在tick内写入的setState方法。
答案 1 :(得分:0)
在Clock.jsx中输入componentWillMount()而不是componentWillUnmount()时出错了。
旧代码片段:
componentWillMount() {
clearInterval(this.timerID)
}
修正:
componentWillUnmount() {
clearInterval(this.timerID)
}