Flatlist keyExtractor returns "TypeError: null is not an object" when data is null

Flatlist keyExtractor returns "TypeError: null is not an object" when data is null

我有以下 React Native Flatlist:

<FlatList
            data={dataOnDevice}
            renderItem={({ item }) => {
              return (
                <RowItem
                  id={item.id}
                  key={item.id}
                  text={`ID: ${item.id} Name: ${item.name} Group: ${item.group}`}
                  onPress={() => {
                    navigation.pop();
                  }}
                  rightIcon={
                    <View style={styles.icon}>
                      <Entypo name="trash" size={20} color={colors.white} />
                    </View>
                  }
                />
              );
            }}
            ItemSeparatorComponent={() => <RowSeparator />}
            ListFooterComponent={() => (
              <View style={{ paddingBottom: insets.bottom }} />
            )}
            ListEmptyComponent={() => listEmptyComponent()}
            keyExtractor={(item) => item.id.toString()}
          />

当我在列表中有数据时这工作正常但是当 dataOnDevicenull 时,我得到一个错误:

TypeError: null is not an object (evaluating 'item.id.toString')

这是在导致 dataOnDevice 为空的重构之后发生的。我的理解是 ListEmptyComponent 应该能够处理...

如何使用 keyExtractor 来防止此错误?

现在我找到了解决这个问题的方法:

keyExtractor={(item) => {              
  if (item !== "") {              
    item.id.toString();             
  }            
}}

但我愿意接受任何更简洁的处理方式...

您应该检查 ID 是否不为空

在 keyExtractor

  if (item?.id !== "") {              

通过?如果不存在则检查该值是否存在 return false

这样你就可以知道你正在接近一个现有值并避免异常拍摄

阅读更多关于 Ternary Operator