scrollToIndex 超出范围:项目长度为 0 但最小值为 1

scrollToIndex out of range: item length 0 but minimum is 1

我的水平 FlatList 可以很好地处理虚拟数据,但是当我尝试将数据从后端传递到我的 FlatList 它 returns 错误 scrollToIndex out of range: requested index -1 but minimum is 0.

垂直方向的数据传递正确FlatList但是当我尝试使用水平方向的数据时,它给出了这个错误。

你认为我的横向 FlatList 代码有什么问题?

useEffect(() => {
    const getIndex = (placeholder = 0) => {
        const index = places.findIndex(place => place.id === selectedPlaceId);
        if (index === -1) return placeholder;
        return index;
    };

    const index = getIndex();

    flatlist.current.scrollToIndex({index});

    const selectedPlace = places[index];
    const region = {
        latitude: selectedPlace.coordinate.latitude,
        longitude: selectedPlace.coordinate.longitude,
        latitudeDelta: 0.8,
        longitudeDelta: 0.8
    }

    map.current.animateToRegion(region);

}, [selectedPlaceId])


return (
    <FlatList
         ref={flatlist}
         data={trips}
         renderItem={({ item }) => <PostCarouselItem post={item} />}
         horizontal
         showsHorizontalScrollIndicator={false}
         snapToInterval={width - 70}
         snapToAlignment={"center"}
         decelerationRate={"fast"}
         viewabilityConfig={viewConfig.current}
         onViewableItemsChanged={onViewChanged.current}
         style={{ bottom: 10, left: 0, right: 0, position: "absolute", }}
         contentContainerStyle={{ marginHorizontal: cardWidth }}
         ListFooterComponent={<View style={{marginRight: (cardWidth * 2)}}/>}
    />
);

Array.findIndex returns -1 如果没有找到符合条件的元素。

您需要检查您的条件并为索引值添加验证。

例如:

useEffect(() => {
    const getIndex = (placeholder = 0) => {
        const index = places.findIndex(place => place.id === selectedPlaceId);
        if (index === -1) return placeholder;
        return index;
    };

    const index = getIndex();

    if (index < trips.length) {
        flatlist.current.scrollToIndex({index});
    }

    const selectedPlace = places[index];
    const region = {
        latitude: selectedPlace.coordinate.latitude,
        longitude: selectedPlace.coordinate.longitude,
        latitudeDelta: 0.8,
        longitudeDelta: 0.8
    }

    map.current.animateToRegion(region);

}, [places, selectedPlaceId, trips])