You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native嵌套列表遍历报错:undefined is not an object (evaluating item.key)

Fixing "undefined is not an object (evaluating item.key)" in React Native Nested Lists

Hey there! Let's figure out why you're running into that frustrating error and get your nested fields displayed properly.

Common Causes of the Error

First, let's break down what's likely going wrong:

  • You might be targeting the wrong level of your nested data (e.g., trying to access key on an outer-level object instead of the inner field items).
  • Your data might not actually have a key property on the items you're trying to iterate over.
  • You could have mixed up variable names in your nested render functions, leading to trying to access key on an undefined value.

Step-by-Step Solution

Let's start with a sample data structure that matches what you described (items with a fields array containing field and value), then build the correct nested FlatList implementation.

Sample Data

const nestedData = [
  {
    id: "group-1",
    items: [
      {
        fields: [
          { field: "Username", value: "guillaume_p", key: "user-1-username" },
          { field: "Email", value: "guillaume@example.com", key: "user-1-email" }
        ],
        key: "user-1"
      },
      {
        fields: [
          { field: "Username", value: "jane_doe", key: "user-2-username" },
          { field: "Age", value: 28, key: "user-2-age" }
        ],
        key: "user-2"
      }
    ]
  }
];

Working Nested FlatList Code

import React from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';

const NestedFieldList = () => {
  // Render individual field entries
  const renderField = ({ item }) => {
    // Guard against missing data with optional chaining
    if (!item?.field || !item?.value) return null;
    
    return (
      <View style={styles.fieldRow}>
        <Text style={styles.fieldLabel}>{item.field}</Text>
        <Text style={styles.fieldValue}>: {item.value}</Text>
      </View>
    );
  };

  // Render each item that contains a fields array
  const renderListItem = ({ item }) => {
    // Make sure the item has a fields array before rendering
    if (!item?.fields) return null;
    
    return (
      <View style={styles.itemContainer}>
        <FlatList
          data={item.fields}
          renderItem={renderField}
          // Use the key from the inner field item
          keyExtractor={(fieldItem) => fieldItem.key}
          // Disable scrolling for inner lists if not needed
          scrollEnabled={false}
        />
      </View>
    );
  };

  return (
    <FlatList
      // Target the inner items array from your data
      data={nestedData[0].items}
      renderItem={renderListItem}
      // Use the key from the outer list item
      keyExtractor={(listItem) => listItem.key}
      style={styles.container}
    />
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
    backgroundColor: '#f5f5f5',
  },
  itemContainer: {
    backgroundColor: 'white',
    padding: 12,
    borderRadius: 8,
    marginBottom: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  fieldRow: {
    flexDirection: 'row',
    marginVertical: 4,
  },
  fieldLabel: {
    fontWeight: '600',
    fontSize: 14,
  },
  fieldValue: {
    fontSize: 14,
    color: '#333',
  },
});

export default NestedFieldList;

Key Fixes to Note

  1. Correct Data Targeting: Make sure you're passing the right array to each FlatList. In the example, we use nestedData[0].items for the outer list (since our data is wrapped in a top-level array), and item.fields for the inner list.
  2. Proper Key Extraction: Each FlatList needs its own keyExtractor that references the correct item's unique identifier. The outer list uses the key from each item in the items array, while the inner list uses the key from each field entry.
  3. Guard Clauses & Optional Chaining: Using ?. (optional chaining) and null checks prevents crashes if any part of your data is missing or undefined. For example, item?.fields ensures we don't try to render a FlatList with undefined data.

If Your Data Doesn't Have key Properties

If your original data doesn't include key fields, you can create a unique identifier using existing properties:

// For inner field items
keyExtractor={(fieldItem) => `${fieldItem.field}-${fieldItem.value}`}

// Or use index as a last resort (not ideal for dynamic lists)
keyExtractor={(item, index) => index.toString()}

内容的提问来源于stack exchange,提问作者Guillaume Piedigrossi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:16:35