React Native FlatList滚动加载出现重复Key错误求助
React Native FlatList滚动加载时Key重复问题排查
问题描述
ERROR Warning: Encountered two children with the same key,
4. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
开发支持滚动加载的React Native FlatList时出现上述Key重复警告,已排查数小时未找到原因,相关代码如下:
相关代码
数据获取与加载更多函数
const getProducts = (itemId, check, multiSliderValue, offset) => { return new Promise((resolve, reject) => { dispatch( authAction.GetAllProducts( itemId, check, brand, multiSliderValue, offset ) ).then((response) => { // 复制现有数据列表 const updatedList = [...informations]; let counter = informations.length; const newArray = response.array.map((item) => ({ ...item, key: counter++, // 使用递增计数器作为唯一key })); if (newArray.length > 0) { setInformations([...updatedList, ...newArray]); setOffset(offset + 5); } setIsLoading(false); resolve(newArray); }); }); }; const loadMoreData = () => { if (isLoading) { return; // 防止重复调用加载函数 } console.log(itemId, check, multiSliderValue, offset + 5); setIsLoading(true); getProducts(itemId, check, multiSliderValue, offset) .then((response) => { if (response) { // 更新数据列表 setInformations([...informations, ...response]); // 更新偏移量 setOffset(offset + 5); } else { console.log("NO RESPONSE"); } }) .catch((error) => { console.log("error: ", error); }) .finally(() => { setIsLoading(false); }); };
FlatList组件代码
<FlatList onEndReachedThreshold={0.5} onEndReached={loadMoreData} ListFooterComponent={isLoading ? <ActivityIndicator /> : null} style={{top: "2%"}} data={informations} renderItem={({item}) => ( <View style={styles.Products}> <TouchableOpacity onPress={() => navigation.navigate("descriptionProduct", { data: item, }) } > <View style={{width: "40%", height: "60%"}}> <Image style={styles.imageProduct} source={{uri: item.image_url}} /> </View> <View style={styles.productInfos}> <View style={{width: "60%", height: "30%"}}> <Text style={{ fontSize: 15, bottom: "340%", }} > {item.titre} </Text> </View> <View style={{ display: "flex", flexDirection: "row", bottom: "1%", }} > <Text style={{color: "grey"}}>à partir de </Text> <Text style={styles.price}>{item.prix} €</Text> <Text style={{left: "50%", color: "grey"}}> {item.boutiqueCpt} offres </Text> </View> </View> </TouchableOpacity> </View> )} />
初始化useEffect钩子
useEffect(() => { if (isLoading) { return; // 防止重复调用加载函数 } getBrands(itemId); getProducts(itemId, check, multiSliderValue, offset); setIsLoading(true); }, [dispatch]);
求助需求
请解释错误原因并提供解决方案,提前感谢。
内容的提问来源于stack exchange,提问作者Nicolas
相关产品推荐
相关产品推荐

