首页 > 解决方案 > 反应 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 还很陌生,但我认为可能是每次更新时都会创建一个新间隔。如果是这种情况,我该怎么做?

是的,我知道它只是放在那里的随机数,这只是发展:)

标签: reactjssetstate

解决方案


在生命周期方法中设置间隔,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>
  );
}

推荐阅读