防止项目背景颜色更改平面列表

Prevent Item Background Color From Changing Flatlist

我有一个 FlatList,它正在从用户的 phone 获取联系。我想从十六进制颜色代码数组中为每个没有头像的联系人提供随机颜色,我称之为“CircleColors”。

这就是我正在尝试的:

 <FlatList
          data={filteredContacts}
          renderItem={({ item }) => (
            <View key={uuidv4()} style={styles.contactItem}>
              <View style={item.avatar && styles.contactAvatar}>
                {item.avatar && (
                  <Image
                    style={{
                      borderRadius: 50,
                      width: 50,
                      height: 50,
                    }}
                    source={{
                      uri: item.avatar,
                    }}
                  />
                )}
                {!item.avatar && (
                  <ContactItem
                    itemData={item.name}
                    color={
                      CircleColors[
                        Math.floor(Math.random() * CircleColors.length)
                      ]
                    }
                  />
                )}
              </View>
              <View>
                <Text style={styles.contactTxt}>{`${item.name}`}</Text>
                <Text
                  style={
                    item.usernames.length
                      ? styles.contactUser
                      : styles.noUser
                  }
                >
                  {item.usernames.length ? `$${item.usernames}` : null}
                </Text>
              </View>
            </View>
          )}
        />

这里是联系人项目的代码:

const ContactItem = ({ itemData, color }) => {
return (
  <View
    style={[
      styles.userCircle,
      {
        backgroundColor: color,
      },
    ]}
  >
    <Text style={styles.userCircleTxt}>
      {itemData.substr(0, 1).toUpperCase()}
    </Text>
  </View>
);

};

问题是在滚动时,平面列表会重新呈现每个项目,并且每次都会更改颜色。有没有办法保留给每个项目背景的原始随机颜色,即使在滚动时也是如此?

如有任何帮助,我们将不胜感激。

谢谢!

这一行出现问题

<View key={uuidv4()} style={styles.contactItem}>

key总是变的,你应该将index传递给key

renderItem={({ item,index }) => (
    <View key={index} style={styles.contactItem}>

将键作为索引和动态背景颜色样式传递到数组中,如下所示 -

renderItem={({ item,index }) => (
    <View key={index} style={[{item.background},styles.contactItem]}>