[英]Filter data in React Native Section List
I'm using React Native's SectionList. 我正在使用React Native的SectionList。 The data to the SectionList looks something like this
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"]
}
]
I have a Text Input using which I try to filter out contents in the SectionList. 我有一个文本输入,尝试通过它过滤掉SectionList中的内容。 I tried using
Array.filter()
and it doesn't seem to work. 我尝试使用
Array.filter()
,它似乎不起作用。 It returns me the entire data without any filtering. 它返回我全部数据,而没有任何过滤。 So, I tried
Array.some()
. 因此,我尝试了
Array.some()
。 Now all the data items in the section are being filtered when even one item matches it. 现在,即使有一项匹配,也会过滤该部分中的所有数据项。 This behavior is expected out of
Array.some()
. Array.some()
可能会出现此行为。 But I'm confused why Array.filter()
is not working in my case. 但是我很困惑为什么
Array.filter()
在我的情况下不起作用。
My SectionList looks something like this, 我的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}
/>
Here's the link for Expo Playground if you wish to play with it online. 如果您想在线玩世博游乐场 ,请点击这里。
filter
will create a new array with all the entries that returned a truthy value. filter
将创建一个包含所有返回真实值的条目的新数组。 Your second filter will always return at least an empty array, which is truthy, and thus you get all your sections in the final result. 您的第二个过滤器将始终至少返回一个空数组,这是事实,因此您可以在最终结果中获得所有节。
You could try a combination of reduce
and filter
instead: 您可以尝试结合使用
reduce
和filter
:
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;
}, [])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.