在 React Native Section 列表中过滤数据

IT技术 javascript reactjs react-native react-native-sectionlist
2021-05-02 05:12:49

我正在使用 React Native 的 SectionList。SectionList 的数据看起来像这样

data: [
    {
      title: "Asia",
      data: ["Taj Mahal", "Great Wall of China", "Petra"]
    },
    {
      title: "South America",
      data: ["Machu Picchu", "Christ the Redeemer", "Chichen Itza"]
    },
    {
      title: "Europe",
      data: ["Roman Colosseum"]
    }
  ]

我有一个文本输入,我尝试使用它过滤掉 SectionList 中的内容。我尝试使用Array.filter()它似乎不起作用。它返回我没有任何过滤的整个数据。所以,我试过了Array.some()现在,即使有一项匹配,该部分中的所有数据项也会被过滤。这种行为是预料之中的Array.some()但我很困惑为什么Array.filter()在我的情况下不起作用。

我的 SectionList 看起来像这样,

<SectionList 
      sections={this.state.data.filter(sectionData => {
        sectionData = sectionData.data;
        return sectionData.filter(data => {
          return data.includes(this.state.searchTerm);
        })
      })}
      renderSectionHeader={({ section: { title } }) => ( <Text style={{ fontWeight: "bold" }}>{title}</Text> )}
      renderItem={({ item }) => ( <Text style={styles.listItem}>{item}</Text>)}
      keyExtractor={item => item}
    />

如果您想在线玩,这里是Expo Playground的链接

1个回答

filter将创建一个包含所有返回真值的条目的新数组。您的第二个过滤器将始终至少返回一个空数组,这是真实的,因此您将在最终结果中获得所有部分。

您可以尝试组合reducefilter代替:

this.state.data.reduce((result, sectionData) => {
  const { title, data } = sectionData;
  const filteredData = data.filter(
    element => element.includes(this.state.searchTerm)
  );

  if (filteredData.length !== 0) {
    result.push({
      title,
      data: filteredData
    });
  }

  return result;
}, [])