React Native では、「scrollToIndex」を使用してフラットリストをスクロールしようとしています。これは、最後のページの 1 つから最初のページ (インデックス 0) に移動するまでは問題なく機能します。次に、「renderItem」が呼び出されず、フラットリストによってレンダリングされると予想されるページ/アイテムではなく、空のページが表示されます。
私が取ったステップ:
最初に、コンポーネントにフック ref を作成しました。
const flatListRef = React.createRef();
次に、フラットリストをコンポーネント レンダリングに追加しました。
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>
);
次に、フラットリストをインデックス 8 から 0 にスクロールする useEffect を追加しました。
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]);
そして最後に、フラットリストのデータを追加しました:
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」を呼び出さないため、空のページが表示されます。