【问题标题】:How to notify a component that it needs to update如何通知组件需要更新
【发布时间】:2019-07-01 06:53:12
【问题描述】:

正如您在下面的代码中看到的,我每 100 毫秒检查一次(使用 setInterval)是否对 convertProgress 进行了更改,如果是,则组件需要更新。

class TradingThing extends React.Component {
  componentDidMount() {
    const { convertProgress, setConvertProgress } = this.props.store; // mobx store
    this.interval = setInterval(() => {
         if(convertProgress < 100) {
             setConvertProgress(Math.min(convertProgress + 5, 100));
         }
    , 100);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return (
        <div>Progress from MobX state: {this.props.store.convertProgress}</div>
    );
  }
}

我该如何处理? 每100ms调用一个空函数可以吗?

注意:我不允许在rendercomponentWillUpdatecomponentDidUpdategetSnapshotBeforeUpdate 中调用setStatefunction。

【问题讨论】:

  • 为什么必须每 100 毫秒调用一次?进度完成就不能触发事件吗?
  • @YoavKadosh 感谢您的关注。我需要根据propfalse 更改为true 来重置计时器。我想知道每 100 毫秒计数的成本。 :D
  • 您是否可以利用某种发布-订阅机制?这将比使用setInterval 更高效
  • @YoavKadosh 抱歉。 “发布-订阅”是什么意思?
  • 发布 - 订阅模式。您可以使用它在需要更新时“通知”您是组件,而不是每 100 毫秒轮询一次。有点像 JavaScript 中事件的工作方式。一旦进度 = 100,将触发一个事件,并且您的组件(将监听该事件)将在那时更新。

标签: reactjs performance setinterval


【解决方案1】:

与其轮询每个100ms,更好的方法是利用某种Publish-Subscribe 机制。这种机制允许您在需要更新时“通知”您的组件,而不是不断(且冗余地)检查是否需要更新。

JavaScript 中的事件是发布-订阅模式的一个很好的例子。

有很多方法可以实现,但这里是这个概念的一个基本示例:

// This class is utilizing the publish-subscribe pattern
class ProgressUpdater {
  static subscribers = [];

  static publish(progress) {
    this.subscribers.forEach(s => s(progress));
  }

  static subscribe(subscriber) {
    this.subscribers.push(subscriber);
  }
}

那么你的进程应该通过调用来发布它的进度:

ProgressUpdater.publish(progress);

并且你的组件应该subscribecomponentDidMount中的进度更新事件:

class App extends React.Component {
  state = {progress: 0}

  componentDidMount() {
    ProgressUpdater.subscribe(progress => {
        this.setState({progress});
    })
  }

  render() {
    return (
      <div className='progress'>Progress: {this.state.progress}</div>
    )
  }
}

这是一个fiddle,看看它是如何协同工作的

【讨论】:

  • 发布-订阅机制的好文章!我学到了很多东西!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多