报错提示如下:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Timer component.
这里是我的代码(这里的props是接受另外一个组建传过来的数据):
class Timer extends PureComponent {
static propTypes = {
aim: PropTypes.number
};
constructor(props) {
super(props);
this.state = {
num: 0,
days: 0
}
}
tick() {
if (this.props.aim) {
const aimTime = new Date(this.props.aim);
const currentTime = Date.parse(new Date());
const leftTime = aimTime - currentTime;
const day = aimTime.getDate();
const hours = aimTime.getHours();
this.setState({
num: hours,
days: day
}, () => {
if (currentTime === this.props.aim) {
clearInterval(this.interval);
}
});
}else{
this.setState({
num: 0,
days: 0
})
}
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillMount(){
clearInterval(this.interval);
}
render() {
return (
<span>还剩 {this.state.days} 天 {this.state.num} 小时</span>
);
}
}
这里附上stackflow里的答案,但是看了下不是很清楚。点击链接
在componentWillUnmount生命周期把你这个定时器clear掉