【问题标题】:react setState interval反应 setState 间隔
【发布时间】:2018-05-14 15:17:20
【问题描述】:

我正在使用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 还很陌生,但我认为可能是每次更新时都会创建一个新的间隔。如果是这种情况,我该怎么做?

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

【问题讨论】:

  • 我也找到了解决方案。不过,感谢您的帮助。

标签: reactjs setstate


【解决方案1】:

在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>
  );
}

【讨论】:

  • 不客气。请记住,这是一种不好的做法,您不应直接通过 render 方法更新组件的状态。
  • @YaakovAinspan 现在你可以考虑接受它,如果答案仍然对你有用! :D :)
猜你喜欢
  • 2016-10-14
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 2019-08-27
  • 2021-07-12
  • 2017-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多