gpt4 book ai didi

reactjs - react 设置状态间隔

转载 作者:行者123 更新时间:2023-12-02 17:08:51 25 4
gpt4 key购买 nike

我正在使用 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>
);
}

但是,它一直在数字之间闪烁,正如您在 this video 中看到的那样.我不确定这是为什么,因为我是 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>
);
}

关于reactjs - react 设置状态间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50333787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com