首页 > 解决方案 > 如何在 React 本机 FlatList 中加载两个状态,可以吗?

问题描述

我在下面有两个状态。

state={
   title=['abc','def','ghi'];    //data for-example.
   Subheading=['aaa','bbb','ccc']; //data for-example.
}

我想通过 FlatList 跟踪输出。

abc
aaa

def
bbb

ghi
ccc

我尝试过的代码只能加载标题状态,但如何在文本组件中加载子标题和标题。

我的代码类似:

 <FlatList
       style={{ flex: 1, padding: 9 }}
       data={Object.assign(this.state.title)}
       keyExtractor={(key, index) => key + index}
       renderItem={(itemData) => {

         return <Card.Title
                 title={itemData.item}
                 subtitle={<Text>//how to load subheading</Text>}
                 onPress={() => console.log("Pressed")}>
                 />
             }
           }
   />

标签: javascriptreactjsreact-native

解决方案


有几种方法可以做到这一点,但我认为更简洁的方法是将数组合并到这种形式的对象中[{ title: 'aaa', subtitle: 'abc' }]

const data = title.map( (item,index) => {
       return { title: item, subtitle: Subheading[index] }
}

然后在您的平面列表中,您可以使用item.titleitem.subtitle

从程序员的角度来看,我将始终以结构化和可读的方式组织我的数据,以便最终我的渲染代码也将是可读的(而不是多个数组 [index])


推荐阅读