scrollToIndex Flatlist 从最后一项到第一项导致空屏幕

时间:2021-03-28 18:31:35

标签: reactjs react-native native flatlist scrolltoindex

在 React Native 中,我试图在“scrollToIndex”的帮助下在平面列表中滚动。这工作正常,直到我想从最后一页之一转到第一页(索引 0)。然后不调用“renderItem”,我看到一个空页面,而不是 flatlist 预期呈现的页面/项目。

我采取的步骤:

首先我在组件中创建了一个钩子引用: const flatListRef = React.createRef();

然后我将 flatlist 添加到组件渲染中:

return (
    <View
      style={{
        flex: 1,
      }}
    >
      <FlatList
        ref={flatListRef}
        horizontal
        pagingEnabled
        bounces={false}
        showsHorizontalScrollIndicator={false}
        initialScrollIndex={8}  // I want to go to the last index, this example 8 but it could be 500.
        maxToRenderPerBatch={1} // For performance I put the items to render as low as possible
        initialNumToRender={1}  // ""
        windowSize={1}          // ""
        data={chapters()}
        getItemLayout={(data, index) => ({
          length: width,
          offset: width * index,
          index,
        })}
        viewabilityConfig={{
          itemVisiblePercentThreshold: 50,
        }}
        keyExtractor={item => item.chapter.toString()}
        renderItem={({item}) => (
          <View style={{width, flex: 1}}>
            {console.log('rendered!', item.chapter)}
            <Text style={{ marginTop: 300, textAlign: 'center' }} >It loads all pages when scrolling horizontally from the last to the first renderedItem. This is chapter: {item.chapter}</Text>
          </View>
        )}
      />
    </View>
  );

然后我添加了一个 useEffect 将平面列表从索引 8 滚动到 0:

  React.useEffect(() => {
    setTimeout(() => {
      // The initialScrollIndex is 8. I wait 5 seconds and then tell React to scroll to the first item (index 0). 
      console.log('calling scrollToIndex...');
      flatListRef?.current?.scrollToIndex({ animated: false, index: 0 }); 
      // Also tried scrollToItem but with the same result
    }, 5000);
  }, [flatListRef]);

最后我添加了 flatlist 的数据:

const chapters = () => {
    return [
      {
        chapter: '1',
        title: 'chapter 1',
      },
      {
        chapter: '2',
        title: 'chapter 2',
      },
      {
        chapter: '3',
        title: 'chapter 3',
      },
      {
        chapter: '4',
        title: 'chapter 4',
      },
      {
        chapter: '5',
        title: 'chapter 5',
      },
      {
        chapter: '6',
        title: 'chapter 6',
      },
      {
        chapter: '7',
        title: 'chapter 7',
      },
      {
        chapter: '8',
        title: 'chapter 8',
      },
      {
        chapter: '9',
        title: 'chapter 9',
      },
    ];
  };

预期行为: 它加载最后一页,5 秒后它应该打开第一个项目/页面(索引 0)并成功渲染。

实际行为: 它加载最后一页,5 秒后打开第一页,但平面列表不调用“renderItem”,因此显示一个空页面。

Example on Snack

0 个答案:

没有答案