反应设置状态间隔

react setState interval

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