gpt4 book ai didi

react-native - 在 React Native 中循环遍历嵌套数组

转载 作者:行者123 更新时间:2023-12-04 04:06:45 28 4
gpt4 key购买 nike

我正在尝试在我的 React native 应用程序中遍历嵌套数组。

我尝试使用 for 循环,但这不起作用。我还是 React 的新手,所以我不太熟悉如何循环

现在我要做的是只显示来自 newRow 的数据。在来自 row 的每个对象中大批

使用 { item.newRow[0].name }确实有效我想循环播放 newRow显示所有新行

如何遍历所有行并获取所有 newRows要显示?

示例数组:

  {
id: 0,
text: 'View',
newRow: [
{id: 0, text: 'View'},
{id: 1, text: 'Text'},
{id: 2, text: 'Image'},
{id: 3, text: 'ScrollView'},
{id: 4, text: 'ListView'},
]
},
{id: 1, text: 'Text',
newRow: [
{id: 0, text: 'View'},
{id: 1, text: 'Text'},
{id: 2, text: 'Image'},
{id: 3, text: 'ScrollView'},
{id: 4, text: 'ListView'},
]
},
{id: 2, text: 'Image'},
{id: 3, text: 'ScrollView'},
{id: 4, text: 'ListView'},

示例代码:
import React, { Component } from 'react';
import { FlatList, Text, StyleSheet,View } from 'react-native';

const rows = [
{
id: 0,
text: 'View',
newRow: [
{id: 0, text: 'View'},
{id: 1, text: 'Text'},
{id: 2, text: 'Image'},
{id: 3, text: 'ScrollView'},
{id: 4, text: 'ListView'},
]
},
{id: 1, text: 'Text',
newRow: [
{id: 0, text: 'View'},
{id: 1, text: 'Text'},
{id: 2, text: 'Image'},
{id: 3, text: 'ScrollView'},
{id: 4, text: 'ListView'},
]
},
{id: 2, text: 'Image'},
{id: 3, text: 'ScrollView'},
{id: 4, text: 'ListView'},

]

// const rowsNewRow = rows[i].newRow

const extractKey = ({newRow}) => newRow

export default class App extends Component {

renderItem = ({item}) => {
return (
<Text style={styles.row}>
{item.text}
</Text>
)
}

renderLoop = ({item}) => {
var items= [];

for(let i = 0; i < item; i++){

items.push(
<View key = {i}>
<View>
<Text style={styles.row}>
{item.text}
</Text>
</View>
<View>

</View>
<View>

</View>
</View>
)
}
}

render(

) {
return (
<View style={styles.container}>

<FlatList
style={styles.container}
data={rows}
renderItem={this.renderItem}
keyExtractor={extractKey}
/>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
marginTop: 20,
flex: 1,
},
row: {
padding: 15,
marginBottom: 5,
backgroundColor: 'skyblue',
},
})

Example App

最佳答案

听起来您正在考虑将 newRow 数组中的项目包含在您在 FlatList 中创建的行中。

这可以通过更新您的 renderItem 来实现。起到这样的作用

renderItem = ({item}) => {
let items = [];
if( item.newRow) {
items = item.newRow.map(row => {
return <Text>{row.text}</Text>
})
}

return (
<View>
<Text style={styles.row}>
{item.text}
</Text>
{items}
</View>
)
}

我正在做的是
  • 创建一个空数组来保存映射的 newRow项目
  • 检查 newRow数组存在
  • 如果它存在,那么我将它映射到一个数组
  • 更新返回函数,使其返回所有项目

  • 这是带有工作代码的小吃 https://snack.expo.io/@andypandy/flatlist-with-nested-array

    关于react-native - 在 React Native 中循环遍历嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54390652/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com