2017-05-08 314 views
3

我使用新的FlatList component并希望在生命周期方法(如componentDidMount)中使用ScrollToIndex(或ScrollToEnd)。FlatList组件生命周期方法ScrollToIndex ScrollToEnd等

我有一个让我们说100个项目的数组,我不想开始渲染第一个项目,但在开始。让我们说在第50项。当FlatList仅一次显示一个项目,它的工作根据需要与一些黑客如下所述:https://github.com/facebook/react-native/issues/13202

componentDidMount() { 
    let wait = new Promise((resolve) => setTimeout(resolve, 500)); // Smaller number should work 
    wait.then(() => { 
    this.refs.flatlist.scrollToIndex({index: 4, animated: true}); 
    }); 
} 

这个片段使得scrollToIndex运行一些componentDidMount调用的毫秒。

但是,当我使用FlatList其中视图包含3x3网格,我根本无法使它运行。当我使用scrollToIndex并且索引超出指定的道具initialNumToRender时,我只收到一个我无法理解的错误scrollIndex out of range $ID。提供的数据数组包含所有的数据,例如100个项目。当我使我们成为scrollToEnd时,它只停留在中间的某个地方而不是最后。对我来说,它看起来像某种错误,我不知道如何在初始渲染后滚动到$ X项目。你可以帮我吗?

我很感激任何形式的帮助或评论。

我在iOS和Android(仿真器和设备)上尝试了React-Native v0.43.0和v0.44.0,它总是一样的。

回答

1

看着VirtualizedList.js,scrollIndex out of range $ID警告在这些条件下发生:

scrollToIndex(params: {animated?: ?boolean, index: number, viewPosition?: number}) { 
    const {data, horizontal, getItemCount} = this.props; 
    const {animated, index, viewPosition} = params; 
    if (!(index >= 0 && index < getItemCount(data))) { 
     console.warn('scrollToIndex out of range ' + index); 
     return; 
    } .... 

也许检查你的道具getItemCount越来越从给定的数据正确的计数。默认情况下,道具使用data.length,因此如果尚未拥有,您可能需要指定自己的道具。

3

您是否在FlatList上设置了getItemLayout prop?

检查它在scrollToIndex的阵营本地代码说 - 如果你的项目有一组高度虽然https://github.com/facebook/react-native/blob/master/Libraries/Lists/FlatList.js#L308

这只会真正发挥作用。似乎没有适合高度可变的物品的解决方案。我只设置了initialNumToRender={indexToScrollTo + 1},然后使用scrollToOffset而不是scrollToIndex(将偏移量设置为您要滚动到的项目的偏移量),从而设法通过设置变量高度来实现此目的。这具有明显的性能问题,并且如果您的列表很长或者您的项目具有复杂的渲染效果,那么这真是不理想。