gpt4 book ai didi

reactjs - React Native FlatList onViewableItemsChanged 回调在状态改变重新渲染后遇到错误

转载 作者:行者123 更新时间:2023-12-04 15:17:19 27 4
gpt4 key购买 nike

我需要设置状态来检测当前视口(viewport)中的哪个项目是可见的。为此,我编写了以下代码:

const [inViewPort, setInViewPort] = useState(0);

const viewabilityConfig = {
viewAreaCoveragePercentThreshold: 30,
};

const onViewableItemsChanged = ({viewableItems, changed}) => {
if (changed && changed.length > 0) {
setInViewPort(changed[0].index);
}
};

return (
<SafeAreaView style={styles.container}>
<FlatList
data={myData}
renderItem={renderItem}
showsHorizontalScrollIndicator={false}
keyExtractor={(_, index) => index.toString()}
horizontal={true}
onViewableItemsChanged={onViewableItemsChanged}
viewabilityConfig={viewabilityConfig}
/>
</SafeAreaView>
);

onViewableItemsChanged 事件回调正确触发,但在我调用 setInViewPort 后组件更新并重新呈现以下错误:

Invariant Violation: Changing onViewableItemsChanged on the fly is not supported

enter image description here

最佳答案

我一直在寻找相同的答案,但在任何地方都没有明确的例子。我就是这样解决的。

const [inViewPort, setInViewPort] = useState(0)

const viewabilityConfig = useRef({
itemVisiblePercentThreshold: 50,
waitForInteraction: true,
minimumViewTime: 5,
})

const onViewableItemsChanged = React.useRef(({ viewableItems, changed }) => {
if (changed && changed.length > 0) {
setInViewPort(changed[0].index);
}
})

return (
<SafeAreaView style={styles.container}>
<FlatList
data={myData}
renderItem={renderItem}
showsHorizontalScrollIndicator={false}
keyExtractor={(_, index) => index.toString()}
horizontal={true}
onViewableItemsChanged={onViewableItemsChanged.current}
viewabilityConfig={viewabilityConfig.current}
/>
</SafeAreaView>
)

关于reactjs - React Native FlatList onViewableItemsChanged 回调在状态改变重新渲染后遇到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64089808/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com