Javascript ReactJS:双向无限滚动建模

Javascript ReactJS:双向无限滚动建模,javascript,html,infinite-scroll,reactjs,Javascript,Html,Infinite Scroll,Reactjs,我们的应用程序使用无限滚动来浏览大量的异构项目列表。有一些皱纹: 我们的用户通常有10000个项目的列表,需要滚动3k+ 这些是丰富的项目,因此在浏览器性能变得不可接受之前,DOM中只能有几百个 这些物品的高度各不相同 这些项目可能包含图像,我们允许用户跳转到特定日期。这很棘手,因为用户可以跳转到列表中需要在视口上方加载图像的点,这样在加载内容时会向下推内容。如果处理失败,则意味着用户可能会跳转到某个日期,但随后会切换到更早的日期 已知的、不完整的解决方案: ()-这只是一个简单的“触底时

我们的应用程序使用无限滚动来浏览大量的异构项目列表。有一些皱纹:

  • 我们的用户通常有10000个项目的列表,需要滚动3k+
  • 这些是丰富的项目,因此在浏览器性能变得不可接受之前,DOM中只能有几百个
  • 这些物品的高度各不相同
  • 这些项目可能包含图像,我们允许用户跳转到特定日期。这很棘手,因为用户可以跳转到列表中需要在视口上方加载图像的点,这样在加载内容时会向下推内容。如果处理失败,则意味着用户可能会跳转到某个日期,但随后会切换到更早的日期
已知的、不完整的解决方案:

  • ()-这只是一个简单的“触底时加载更多”组件。它不会剔除任何DOM,因此它将在数千个项目上死亡

  • ()-显示在顶部插入时如何存储和恢复滚动位置或在底部插入时如何存储和恢复滚动位置,但不能同时存储和恢复两者


我不是在寻找一个完整解决方案的代码(尽管那会很好),而是在寻找一种“反应方式”来模拟这种情况。是否为滚动位置状态?我应该跟踪什么状态才能保留我在列表中的位置?我需要保持什么状态,以便在靠近渲染内容的底部或顶部滚动时触发新渲染?

这是无限表格和无限滚动场景的混合。我发现最好的抽象是:

概述

制作一个
组件,该组件包含一个所有子元素的数组。因为我们不渲染它们,所以只分配它们并丢弃它们是非常便宜的。如果10k分配太大,您可以传递一个函数,该函数接受一个范围并返回元素

<List>
  {thousandelements.map(function() { return <Element /> })}
</List>

{thounandelements.map(函数(){return})}
您的
列表
组件正在跟踪滚动位置,并且只渲染视图中的子对象。它在开始处添加一个大的空div,以伪造之前未渲染的项目

现在,有趣的部分是,一旦渲染了
元素
组件,您就可以测量其高度并将其存储在
列表
中。这使您可以计算间隔的高度,并知道视图中应显示多少图元

图像

你是说,当图像加载时,它们会使所有内容“跳”下来。解决方法是在img标签中设置图像尺寸:
。这样,浏览器不必等到下载后才知道要显示的大小。这需要一些基础设施,但确实值得

如果您无法预先知道大小,请将
onload
侦听器添加到图像中,并在加载图像时测量其显示的尺寸,更新存储的行高并补偿滚动位置

在随机元素处跳跃

如果您需要跳转到列表中的一个随机元素,那么需要对滚动位置进行一些技巧,因为您不知道中间元素的大小。我建议您将已经计算的元素高度取平均值,然后跳转到上一个已知高度+(元素数*平均值)的滚动位置

因为这并不准确,当你回到上一个已知的好位置时,它会引起问题。发生冲突时,只需更改滚动位置即可解决。这将稍微移动滚动条,但不会对他/她造成太大影响

反应细节

您希望为所有渲染元素提供一个属性,以便在渲染过程中维护这些元素。有两种策略:(1)只有n个键(0,1,2,…n),其中n是可以显示和使用其位置模n的最大元素数。(2) 每个元素具有不同的键。如果所有元素共享相似的结构,最好使用(1)重用它们的DOM节点。如果没有,则使用(2)

我只有两个React状态:第一个元素的索引和显示的元素数。所有元素的当前滚动位置和高度将直接连接到此。当使用
setState
时,实际上是在进行重新渲染,这只应在范围改变时发生

下面是一个无限列表,使用了我在这个答案中描述的一些技巧。这将是一项工作,但React绝对是实现无限列表的一个好方法:)

看看 这看起来像是一个功能强大、性能卓越的datagrid,具有类似Excel的功能和惰性加载/优化的呈现(针对数百万行)以及丰富的编辑功能(MIT许可)。 尚未在我们的项目中尝试,但很快就会尝试

一个伟大的资源来搜索像这样的东西也是 在这种情况下,标记搜索非常有用:

我面临着一个类似的挑战,即用异构项目高度建模单向无限滚动,因此用我的解决方案制作了一个npm包:

还有一个演示:

您可以查看逻辑的源代码,但我基本上遵循了上面答案中概述的@Vjeux配方。我还没有解决跳转到某个特定项目的问题,但我希望能很快实现

下面是代码当前的基本情况:

var React = require('react');
var areNonNegativeIntegers = require('validate.io-nonnegative-integer-array');

var InfiniteScoller = React.createClass({
  propTypes: {
    averageElementHeight: React.PropTypes.number.isRequired,
    containerHeight: React.PropTypes.number.isRequired,
    preloadRowStart: React.PropTypes.number.isRequired,
    renderRow: React.PropTypes.func.isRequired,
    rowData: React.PropTypes.array.isRequired,
  },

  onEditorScroll: function(event) {
    var infiniteContainer = event.currentTarget;
    var visibleRowsContainer = React.findDOMNode(this.refs.visibleRowsContainer);
    var currentAverageElementHeight = (visibleRowsContainer.getBoundingClientRect().height / this.state.visibleRows.length);
    this.oldRowStart = this.rowStart;
    var newRowStart;
    var distanceFromTopOfVisibleRows = infiniteContainer.getBoundingClientRect().top - visibleRowsContainer.getBoundingClientRect().top;
    var distanceFromBottomOfVisibleRows = visibleRowsContainer.getBoundingClientRect().bottom - infiniteContainer.getBoundingClientRect().bottom;
    var rowsToAdd;
    if (distanceFromTopOfVisibleRows < 0) {
      if (this.rowStart > 0) {
        rowsToAdd = Math.ceil(-1 * distanceFromTopOfVisibleRows / currentAverageElementHeight);
        newRowStart = this.rowStart - rowsToAdd;

        if (newRowStart < 0) {
          newRowStart = 0;
        } 

        this.prepareVisibleRows(newRowStart, this.state.visibleRows.length);
      }
    } else if (distanceFromBottomOfVisibleRows < 0) {
      //scrolling down, so add a row below
      var rowsToGiveOnBottom = this.props.rowData.length - 1 - this.rowEnd;
      if (rowsToGiveOnBottom > 0) {
        rowsToAdd = Math.ceil(-1 * distanceFromBottomOfVisibleRows / currentAverageElementHeight);
        newRowStart = this.rowStart + rowsToAdd;

        if (newRowStart + this.state.visibleRows.length >= this.props.rowData.length) {
          //the new row start is too high, so we instead just append the max rowsToGiveOnBottom to our current preloadRowStart
          newRowStart = this.rowStart + rowsToGiveOnBottom;
        }
        this.prepareVisibleRows(newRowStart, this.state.visibleRows.length);
      }
    } else {
      //we haven't scrolled enough, so do nothing
    }
    this.updateTriggeredByScroll = true;
    //set the averageElementHeight to the currentAverageElementHeight
    // setAverageRowHeight(currentAverageElementHeight);
  },

  componentWillReceiveProps: function(nextProps) {
    var rowStart = this.rowStart;
    var newNumberOfRowsToDisplay = this.state.visibleRows.length;
    this.props.rowData = nextProps.rowData;
    this.prepareVisibleRows(rowStart, newNumberOfRowsToDisplay);
  },

  componentWillUpdate: function() {
    var visibleRowsContainer = React.findDOMNode(this.refs.visibleRowsContainer);
    this.soonToBeRemovedRowElementHeights = 0;
    this.numberOfRowsAddedToTop = 0;
    if (this.updateTriggeredByScroll === true) {
      this.updateTriggeredByScroll = false;
      var rowStartDifference = this.oldRowStart - this.rowStart;
      if (rowStartDifference < 0) {
        // scrolling down
        for (var i = 0; i < -rowStartDifference; i++) {
          var soonToBeRemovedRowElement = visibleRowsContainer.children[i];
          if (soonToBeRemovedRowElement) {
            var height = soonToBeRemovedRowElement.getBoundingClientRect().height;
            this.soonToBeRemovedRowElementHeights += this.props.averageElementHeight - height;
            // this.soonToBeRemovedRowElementHeights.push(soonToBeRemovedRowElement.getBoundingClientRect().height);
          }
        }
      } else if (rowStartDifference > 0) {
        this.numberOfRowsAddedToTop = rowStartDifference;
      }
    }
  },

  componentDidUpdate: function() {
    //strategy: as we scroll, we're losing or gaining rows from the top and replacing them with rows of the "averageRowHeight"
    //thus we need to adjust the scrollTop positioning of the infinite container so that the UI doesn't jump as we 
    //make the replacements
    var infiniteContainer = React.findDOMNode(this.refs.infiniteContainer);
    var visibleRowsContainer = React.findDOMNode(this.refs.visibleRowsContainer);
    var self = this;
    if (this.soonToBeRemovedRowElementHeights) {
      infiniteContainer.scrollTop = infiniteContainer.scrollTop + this.soonToBeRemovedRowElementHeights;
    }
    if (this.numberOfRowsAddedToTop) {
      //we're adding rows to the top, so we're going from 100's to random heights, so we'll calculate the differenece
      //and adjust the infiniteContainer.scrollTop by it
      var adjustmentScroll = 0;

      for (var i = 0; i < this.numberOfRowsAddedToTop; i++) {
        var justAddedElement = visibleRowsContainer.children[i];
        if (justAddedElement) {
          adjustmentScroll += this.props.averageElementHeight - justAddedElement.getBoundingClientRect().height;
          var height = justAddedElement.getBoundingClientRect().height;
        }
      }
      infiniteContainer.scrollTop = infiniteContainer.scrollTop - adjustmentScroll;
    }

    var visibleRowsContainer = React.findDOMNode(this.refs.visibleRowsContainer);
    if (!visibleRowsContainer.childNodes[0]) {
      if (this.props.rowData.length) {
        //we've probably made it here because a bunch of rows have been removed all at once
        //and the visible rows isn't mapping to the row data, so we need to shift the visible rows
        var numberOfRowsToDisplay = this.numberOfRowsToDisplay || 4;
        var newRowStart = this.props.rowData.length - numberOfRowsToDisplay;
        if (!areNonNegativeIntegers([newRowStart])) {
          newRowStart = 0;
        }
        this.prepareVisibleRows(newRowStart , numberOfRowsToDisplay);
        return; //return early because we need to recompute the visible rows
      } else {
        throw new Error('no visible rows!!');
      }
    }
    var adjustInfiniteContainerByThisAmount;

    //check if the visible rows fill up the viewport
    //tnrtodo: maybe put logic in here to reshrink the number of rows to display... maybe...
    if (visibleRowsContainer.getBoundingClientRect().height / 2 <= this.props.containerHeight) {
      //visible rows don't yet fill up the viewport, so we need to add rows
      if (this.rowStart + this.state.visibleRows.length < this.props.rowData.length) {
        //load another row to the bottom
        this.prepareVisibleRows(this.rowStart, this.state.visibleRows.length + 1);
      } else {
        //there aren't more rows that we can load at the bottom so we load more at the top
        if (this.rowStart - 1 > 0) {
          this.prepareVisibleRows(this.rowStart - 1, this.state.visibleRows.length + 1); //don't want to just shift view
        } else if (this.state.visibleRows.length < this.props.rowData.length) {
          this.prepareVisibleRows(0, this.state.visibleRows.length + 1);
        }
      }
    } else if (visibleRowsContainer.getBoundingClientRect().top > infiniteContainer.getBoundingClientRect().top) {
      //scroll to align the tops of the boxes
      adjustInfiniteContainerByThisAmount = visibleRowsContainer.getBoundingClientRect().top - infiniteContainer.getBoundingClientRect().top;
      //   this.adjustmentScroll = true;
      infiniteContainer.scrollTop = infiniteContainer.scrollTop + adjustInfiniteContainerByThisAmount;
    } else if (visibleRowsContainer.getBoundingClientRect().bottom < infiniteContainer.getBoundingClientRect().bottom) {
      //scroll to align the bottoms of the boxes
      adjustInfiniteContainerByThisAmount = visibleRowsContainer.getBoundingClientRect().bottom - infiniteContainer.getBoundingClientRect().bottom;
      //   this.adjustmentScroll = true;
      infiniteContainer.scrollTop = infiniteContainer.scrollTop + adjustInfiniteContainerByThisAmount;
    }
  },

  componentWillMount: function(argument) {
    //this is the only place where we use preloadRowStart
    var newRowStart = 0;
    if (this.props.preloadRowStart < this.props.rowData.length) {
      newRowStart = this.props.preloadRowStart;
    }
    this.prepareVisibleRows(newRowStart, 4);
  },

  componentDidMount: function(argument) {
    //call componentDidUpdate so that the scroll position will be adjusted properly
    //(we may load a random row in the middle of the sequence and not have the infinte container scrolled properly initially, so we scroll to the show the rowContainer)
    this.componentDidUpdate();
  },

  prepareVisibleRows: function(rowStart, newNumberOfRowsToDisplay) { //note, rowEnd is optional
    //setting this property here, but we should try not to use it if possible, it is better to use
    //this.state.visibleRowData.length
    this.numberOfRowsToDisplay = newNumberOfRowsToDisplay;
    var rowData = this.props.rowData;
    if (rowStart + newNumberOfRowsToDisplay > this.props.rowData.length) {
      this.rowEnd = rowData.length - 1;
    } else {
      this.rowEnd = rowStart + newNumberOfRowsToDisplay - 1;
    }
    // var visibleRows = this.state.visibleRowsDataData.slice(rowStart, this.rowEnd + 1);
    // rowData.slice(rowStart, this.rowEnd + 1);
    // setPreloadRowStart(rowStart);
    this.rowStart = rowStart;
    if (!areNonNegativeIntegers([this.rowStart, this.rowEnd])) {
      var e = new Error('Error: row start or end invalid!');
      console.warn('e.trace', e.trace);
      throw e;
    }
    var newVisibleRows = rowData.slice(this.rowStart, this.rowEnd + 1);
    this.setState({
      visibleRows: newVisibleRows
    });
  },
  getVisibleRowsContainerDomNode: function() {
    return this.refs.visibleRowsContainer.getDOMNode();
  },


  render: function() {
    var self = this;
    var rowItems = this.state.visibleRows.map(function(row) {
      return self.props.renderRow(row);
    });

    var rowHeight = this.currentAverageElementHeight ? this.currentAverageElementHeight : this.props.averageElementHeight;
    this.topSpacerHeight = this.rowStart * rowHeight;
    this.bottomSpacerHeight = (this.props.rowData.length - 1 - this.rowEnd) * rowHeight;

    var infiniteContainerStyle = {
      height: this.props.containerHeight,
      overflowY: "scroll",
    };
    return (
      <div
        ref="infiniteContainer"
        className="infiniteContainer"
        style={infiniteContainerStyle}
        onScroll={this.onEditorScroll}
        >
          <div ref="topSpacer" className="topSpacer" style={{height: this.topSpacerHeight}}/>
          <div ref="visibleRowsContainer" className="visibleRowsContainer">
            {rowItems}
          </div>
          <div ref="bottomSpacer" className="bottomSpacer" style={{height: this.bottomSpacerHeight}}/>
      </div>
    );
  }
});

module.exports = InfiniteScoller;
var React=require('React');
var areNonNegativeIntegers=require('validate.io非负整数数组');
var InfiniteScoller=React.createClass({
道具类型:{
平均元素高度:React.PropTypes.number.isRequired,
容器高度:需要React.PropTypes.number,
preload行开始:React.PropTypes.number