我正在使用setState()更新显示用户未读消息数量的徽章:
updateUnread(){
this.setState({
unreadCount: Math.floor(Math.random() * 100)
});
}
render(){
setInterval(() => this.updateUnread(), 2000);
return (
<div className="wrapper">
<Messages unreadCount={this.state.unreadCount} />
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
但是,正如您在此视频中看到的那样,它会在数字之间不断闪烁。我不确定为什么会这样,因为我对 React 还很陌生,但我认为每次更新时都会创建一个新的间隔。如果是这种情况,我该怎么做?
是的,我知道这只是放在那里的随机数,这只是发展:)
设置在区间componentDidMount的生命周期方法,并确保你不要通过渲染方法直接更新状态。
通过该render方法更新状态是一种不好的做法。它也可能导致性能不佳和无限循环。
您的情况的问题是,在每次重新渲染时,您都会设置一个导致无穷大的新间隔。
您可以这样做:
componentDidMount() {
const intervalId = setInterval(() => this.updateUnread(), 2000);
this.setState({ intervalId })
}
componentWillUnmount() {
// Make sure to clear the interval, on unmount
clearInterval(this.state.intervalId);
}
updateUnread(){
this.setState({
unreadCount: Math.floor(Math.random() * 100)
});
}
render(){
return (
<div className="wrapper">
<Messages unreadCount={this.state.unreadCount} />
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4676 次 |
| 最近记录: |