react-native - 在轮播视图中离开屏幕时出现平面列表参考错误
问题描述
我在 React Native 中有一个自动滚动轮播,一切正常,图像每 X 秒自动滚动一次,也可以手动滚动。
问题是当我离开该屏幕时,我收到以下错误:
这是我的完整代码...
const { width, height } = Dimensions.get("window");
let flatList;
function infiniteScroll(dataList) {
const numberOfData = dataList.length;
let scrollValue = 0,
scrolled = 0;
setInterval(function () {
scrolled++;
if (scrolled < numberOfData) scrollValue = scrollValue + width;
else {
scrollValue = 0;
scrolled = 0;
}
this.flatList.scrollToOffset({ animated: true, offset: scrollValue });
}, 3000);
}
const Carousel = (props) => {
const topTenVideos = useSelector(getTopTenVideos);
const dispatch = useDispatch();
const scrollX = new Animated.Value(0);
let position = Animated.divide(scrollX, width);
const [dataList, setDataList] = useState(topTenVideos);
const isFocused = useIsFocused();
useEffect(() => {
if (isFocused) {
setDataList(topTenVideos);
infiniteScroll(dataList);
}
}, [isFocused]);
const renderRow = (itemData) => {
return (
<CarouselItem
id={itemData.item.id}
img={itemData.item.poster}
title={itemData.item.title}
/>
);
};
return (
<View style={styles.screen}>
<FlatList
ref={(flatList) => {
this.flatList = flatList;
}}
horizontal
data={dataList}
pagingEnabled
scrollEnabled
snapToAlignment="center"
scrollEventThrottle={16}
decelerationRate={"fast"}
showsHorizontalScrollIndicator={false}
onScroll={Animated.event([
{ nativeEvent: { contentOffset: { x: scrollX } } },
])}
keyExtractor={(item, index) => "key" + index}
renderItem={renderRow}
/>
<View style={styles.dotView}>
{dataList.map((_, i) => {
let opacity = position.interpolate({
inputRange: [i - 1, i, i + 1],
outputRange: [0.3, 1, 0.3],
extrapolate: "clamp",
});
return (
<Animated.View
key={i}
style={{
opacity,
height: 8,
width: 8,
borderRadius: 6,
backgroundColor: "white",
margin: 8,
}}
/>
);
})}
</View>
</View>
);
};
它抱怨这条线this.flatList.scrollToOffset({ animated: true, offset: scrollValue }); }, 3000); 这是我的无限滚动功能。
看起来,当屏幕失去焦点时,它仍在搜索this.flatList.scrollToOffset。
解决方案
You are not creating your ref properly
useRef
,如果您使用功能组件或createRef
在类组件的情况下在组件中创建引用,则必须使用钩子
看看这个。
https://reactjs.org/docs/hooks-reference.html#useref
创建您的参考如下。
const flatListRef = useRef(null)
<FlatList
ref={flatListRef}
// other props
/>
flatListRef.current.scrollToOffset({ animated: true, offset: scrollValue }) // access like this.
推荐阅读
- itext - 升级到 iTextSharp v5.5.8+ 后 pdf 无效
- c# - 数据库设计(RPG项目增强)
- python - tkinter 中的数组状态
- ajax - 错误 ajax 无法将参数传递给 Spring Controller
- ios - 变量从另一个 swift 文件更改其值后返回 nil 值
- android - 从 Android 到 Cassandra 的远程查询
- php - Wordpress PHP 调用 MySQL 程序挂起
- oop - Kotlin 中的 OVERRIDE_BY_INLINE
- java - JAXB marshal to string 在不同计算机上的工作方式不同
- spring - Spring Boot Actutor Web 指标 - 禁用(或分组)http_server_requests_seconds_sum