React Native FlatList 在滚动时的显示

4
我正在制作一个flatlist,在其中我显示用户滚动的信息。 但是我不知道为什么会出现以下错误:
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.
我真的不知道为什么会出现"键重复"的问题。这是我的代码:
 const getProducts = (itemId, check, multiSliderValue, offset) => {
    return new Promise((resolve, reject) => {
      dispatch(
        authAction.GetAllProducts(
          itemId,
          check,
          brand,
          multiSliderValue,
          offset
        )
      ).then((response) => {
        // faites une copie de la liste de données avant de l'utiliser comme source pour l'opérateur de décomposition
        const updatedList = [...informations];
        let counter = informations.length;
        const newArray = response.array.map((item) => ({
          ...item,
          key: counter++, // utilisez un compteur incrémental comme clé unique
        }));
        if (newArray.length > 0) {
          setInformations([...updatedList, ...newArray]);
          setOffset(offset + 5);
        }
        setIsLoading(false);
        resolve(newArray);
      });
    });
  };

 const loadMoreData = () => {
    if (isLoading) {
      return; // empêche les appels multiples à la fonction de chargement de données
    }

    console.log(itemId, check, multiSliderValue, offset + 5);
    setIsLoading(true);
    getProducts(itemId, check, multiSliderValue, offset)
      .then((response) => {
        if (response) {
          // mettez à jour votre liste de données avec les nouvelles données
          setInformations([...informations, ...response]);
          // mettez à jour l'offset
          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(() => {
    if (isLoading) {
      return; // empêche les appels multiples à la fonction de chargement de données
    }

    getBrands(itemId);
    getProducts(itemId, check, multiSliderValue, offset);
    setIsLoading(true);
  }, [dispatch]);

我已经搜索了很多小时,但是我没有找到解决方案,所以如果有人能够解释一下给我,非常感谢您提前。

这只是一个警告,不是什么大问题。如果你想解决这个问题,请分享 flatlist 的完整代码,特别是 renderItem 部分。 - Jatin Bhuva
是的,但当我用滚动更新页面时,我得到了1000个警告^^。(我编辑了我的帖子并添加了整个flatlist) - Nicolas
你有每个项目的ID号码信息吗? - Jatin Bhuva
通常是这样的。 - Nicolas
没事,我有点儿傻,我只是在 FlatList 的第一个视图中添加了 key={item.id}。非常感谢您的回复和帮助! - Nicolas
3个回答

3
出现问题的原因是您使用的键有时相同。在代码块中,我并没有看到您实际使用键。请注意,该键在某些优化过程中内部使用。请参阅文档以了解如何添加密钥的详细信息。简而言之,请添加键提取器方法,该方法将返回项目的唯一标识符。
(item: object, index: number) => string;

React Native 文档

如果在渲染项时,有一个唯一的值可用,请考虑添加该值以避免出现警告。不确定这是否是完整代码。


2
将此添加到flatlist中:
keyExtractor={(item, index) => item.key} //here key should be in your information which is unique for each data item in the information

或者

keyExtractor={(item, index) => index}

2

您可以在末尾添加一个 toString 来使用它。

keyExtractor={(item, index) => item.id.toString()}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接