reactjs - 反应 setState 间隔
问题描述
我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>
);
}
但是,正如您在此视频中看到的那样,它一直在数字之间闪烁。我不确定为什么会这样,因为我对 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>
);
}
推荐阅读
- python - 通过循环从基于其他列的列中添加值
- reactjs - react-intl 与 react-testing-library 给出了无效的钩子调用错误
- java - 我可以使用@RepeatedTest 注释JUnit5 获得变量值吗
- excel - 禁止有关修订的 Word 保存提示
- windows - 使用 PowerShell 安装 docker 桌面可执行文件
- mongodb - 我应该在非常小的 mongodb 对象上添加索引吗?
- flutter - 转换未来
在颤振飞镖中进行int - html - 如何在弹出窗口中显示选定的文件预览
- swift - 配置文件“Development XXX”不包括签名证书“Apple Development: Noorul(TXNRY2JRLN)”
- android - 如何使用 Kotlin 协程和 Retrofit2 异步上传大量文件