【问题标题】:scrollToIndex out of range: item length 0 but minimum is 1scrollToIndex 超出范围:项目长度 0 但最小值为 1
【发布时间】:2021-12-01 06:16:55
【问题描述】:

我的水平FlatList 可以很好地处理虚拟数据,但是当我尝试将数据从后端传递到我的FlatList 时,它返回错误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)}}/>}
    />
);

【问题讨论】:

    标签: javascript react-native react-native-flatlist


    【解决方案1】:

    Array.findIndexreturns-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])
    
    

    【讨论】:

    • 谢谢,它显示相同的错误,但项目长度为 0,最小值为 1,我在这里缺少什么?
    • 请将完整的组件代码和当前错误的详细输出添加到您的问题中
    • 你现在可以看看吗,谢谢-
    • 如何填充trips 变量?我现在在 make scrollToIndex 之前添加了额外的检查
    • 感谢您的编辑,现在看来工作正常。对于trips,我正在使用const [trips, setTrips] = useState([]);
    猜你喜欢
    • 2021-06-16
    • 1970-01-01
    • 2021-04-29
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多