首页 > 解决方案 > 如何访问 SectionList 的数据?

问题描述

我正在尝试使用一些数据创建动态 SectionList。我为我的问题创建了一个示例代码,这是我的数据:

const DATAS = [
  (DATA1 = [
    {
      title: "A",
      data: ["X", "Y", "Z"],
    },
    {
      title: "B",
      data: ["F", "O", "F"],
    },
  ]),
  (DATA2 = [
    {
      title: "M",
      data: ["a", "r", "o"],
    },
    {
      title: "T",
      data: ["F", "s", "s"],
    },
  ]),
];

export default DATAS;

我怎样才能访问 DATA1 或 DATA2,

import  DATAS from .....


const Item = ({ title }) => (
  <View style={styles.item}>
    <Text style={styles.title}>{title}</Text>
  </View>
);

function MySectionList(props) {
  
  return (
    <SectionList
      sections={//i have no idea }
      keyExtractor={(item, index) => item + index}
      renderItem={({ item }) => <Item title={item} />}
      renderSectionHeader={({ section: { title } }) => (
        <Text style={styles.header}>{title}</Text>
      )}
    />
  );
}

我真的很困惑。我尝试了很多东西,但仍然无法正常工作。

标签: javascriptreactjsreact-native

解决方案


看起来sections={DATA[0]}会工作。文档显示您必须将数组传递给sections. 由于您DATAS的导出为对象数组的数组,因此您需要选择要传递给组件的数组。


仅显示DATA1

function MySectionList(props) {
  return (
    <SectionList
      sections={DATAS[0]}
      keyExtractor={(item, index) => item + index}
      renderItem={({ item }) => <Item title={item} />}
      renderSectionHeader={({ section: { title } }) => (
        <Text style={styles.header}>{title}</Text>
      )}
    />
  );
}

仅显示DATA1DATA2作为一个列表:

function MySectionList(props) {
  return (
    <SectionList
      sections={DATAS.flat()}
      keyExtractor={(item, index) => item + index}
      renderItem={({ item }) => <Item title={item} />}
      renderSectionHeader={({ section: { title } }) => (
        <Text style={styles.header}>{title}</Text>
      )}
    />
  );
}

注意:如果你想渲染DATA1DATA2作为单独的SectionList对象,你将不得不渲染每个对象到它们自己的列表的映射:

function MySectionList(props) {
  const { dataLists } = props;
  return (
    <>
      {
        dataLists.map(dataList => (
          <SectionList
            sections={dataList}
            keyExtractor={(item, index) => item + index}
            renderItem={({ item }) => <Item title={item} />}
            renderSectionHeader={({ section: { title } }) => (
              <Text style={styles.header}>{title}</Text>
            )}
          />
        ))
      }
    </>
  );
}

MySectionList.propTypes = {
  dataLists: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.instanceOf(Section)))
};

<MySectionList dataLists={DATAS} />

推荐阅读