React Native+Native Base嵌套数组遍历:实现多行ListItem展示
Hey there! I see you're just getting started with React Native and Native Base, and you ran into a common issue with displaying nested array data in a List component. Let's break down what went wrong and get those customer names showing on separate lines.
Why Your Original Code Showed Names on One Line
Your initial code passed the entire customers array to the List's dataArray, then used data.map(item => item.description) inside the renderRow callback. This took all the description values, joined them into a single string, and dumped them into one ListItem—hence why everything was crammed onto a single line.
The Fixed Code
Here's the adjusted version that will render each customer name as its own standalone ListItem:
export default class CustomersScreen extends Component { render() { console.log(customers); return ( <Container style={styles.container}> <Content> {/* First loop through the outer array in your JSON structure */} { customers.map((rowData, index) => { return( {/* Pass the inner customer data array to the List component */} <List dataArray={rowData.data} key={index} renderRow={(customerItem) => { return ( <ListItem key={customerItem.id}> <Text>{customerItem.description}</Text> </ListItem> ) }} /> ) }) } </Content> </Container> ); } }
What Changed & Why
- Loop through the outer array: Your JSON is structured as an array containing one object that holds the
dataarray (your customer list). We first iterate over this outer layer to access the actual customer data. - Target the inner data array: By setting
dataArray={rowData.data}, we tell the List component to iterate over each individual customer object instead of the outer wrapper. - Render one ListItem per customer: The
renderRowcallback now receives a single customer item, so we can directly pullcustomerItem.descriptionand place it in its own ListItem—this ensures each name gets its own line. - Added unique keys: We added
keyprops to both the List and ListItem components. This helps React efficiently update the UI and avoids annoying console warnings about missing keys.
内容的提问来源于stack exchange,提问作者Divya R

