智能地使用 shouldComponentUpdate 来帮助浏览器保持响应



我有一个实时应用程序,可以获取大量数据。结果,在大量处理数据期间,浏览器变得无响应。我正在研究使用PromisesRx,但这些似乎涉及的手术比我目前想要承诺的要多。

我读到shouldComponentUpdate可以用于此目的。会说使用它每秒更新一次是可能的[智能可能是我正在寻找的]以及代码在shouldComponentUpdate中的样子:

var HomePage = React.createClass({
    getInitialState: function() {  
        var stocks = {};
        feed.onChange(function(stock) {
            stocks[stock.symbol] = stock;
            this.setState({stocks: stocks, bid: stock, ask: stock, last: stock, type: stock, undsymbol: stock});
        }.bind(this));
        return {
            stocks: stocks            
        };
    },  
    componentDidMount() {              
        var props = this.props;
    },
    shouldComponentUpdate(nextProps, nextState) {
       // What code would go in here to render 
       // all changes, say every 1 second only?
    },
    etc...
}

可能吗? 是的。 最佳实践? 应该不会。

shouldComponentUpdate应该返回一个布尔值:true是否要运行新的更新/渲染周期,如果没有,false

使用 shouldComponentUpdate 限制渲染的一种方法是进行时间戳比较:

shouldComponentUpdate() {
  const now = Date.now();
  if (!this.lastUpdated || now - this.lastUpdated > 1000) {
    this.lastUpdated = now;
    return true;
  }
  return false;
}

最新更新