如何构建具有实时搜索功能的React Native FlatList
by Vikrant Negi 通过Vikrant Negi如何构建具有实时搜索功能的React Native FlatList (How to build a React Native FlatList with realtime searching ability)If you have ever used a mobile app or build one, then you mus...
by Vikrant Negi
通过Vikrant Negi
如何构建具有实时搜索功能的React Native FlatList (How to build a React Native FlatList with realtime searching ability)
If you have ever used a mobile app or build one, then you must have come across some kind of list — whether it was a long list of contacts, products, countries, or other things.
如果您曾经使用过移动应用程序或构建过移动应用程序,那么您肯定会遇到某种列表-无论是一连串的联系人,产品,国家还是其他东西。
They may seem very simple to an end user. But for developers, displaying a long list of data has always been a pain point when it comes to performant long lists. This is especially true in the apps that are build with React Native.
对于最终用户而言,它们似乎非常简单。 但是对于开发人员而言,显示长数据列表一直是性能长列表的难题。 在使用React Native构建的应用程序中尤其如此。
背景 (Background)
During the initial days of React Native, we had the good old ListView. It had many features which made it very attractive, and it was a default choice for efficiently displaying vertical list of changing data.
在React Native的最初几天,我们使用了很好的旧ListVie w 。 它具有许多功能,非常吸引人,并且它是有效显示更改数据的垂直列表的默认选择。
With time, however, many issues and bugs came up, and there was a point when the React Native team realised that it was time to reinvent the wheel.
随着时间的流逝,出现了许多问题和错误,React Native团队意识到应该重新发明轮子了。
输入平面清单 (Enter FlatList)
On March 2017, Facebook introduced the FlatList component, which is an easier and more performant way to implement simple, performant lists. Not only that — its API is easier to understand than the originalListView. Here is how a simple FlatList looks:
2017年3月,Facebook引入了FlatList组件,这是一种更简单,更FlatList方式来实现简单的性能列表。 不仅如此-它的API比原始的ListView更易于理解。 这是一个简单的FlatList的外观:
<FlatList data={[{title: ‘Title Text’, key: ‘item1’}, …]} renderItem={({item}) => <ListItem title={item.title} />} />
Apart from FlatList, you can also use SectionList for rendering sectioned lists.
除了FlatList ,您还可以使用SectionList呈现分段列表。
下一步是什么 (What’s next)
As I mentioned earlier, ListView was used primarily for displaying long lists of vertical changing data. But long lists of data are as useful as a hammer without the handle. ?
如前所述,ListView主要用于显示垂直变化数据的长列表。 但是,长长的数据列表就像没有柄的锤子一样有用。 ?
Almost all the time, whenever you encounter a long list of data, you are also presented with the ability to search though that data so that you don’t get lost searching.
几乎所有时间,每当遇到一长串数据时,您都可以搜索这些数据,从而不会丢失搜索结果。
React本地可搜索的FlatList (React Native Searchable FlatList)
I decided to build something to solve this problem. You can find the complete project repo here.
我决定建立一些解决此问题的方法。 您可以在此处找到完整的项目存储库。
If you are not familiar with the FlatList, I would recommend going through the basics of FlatList first. This article one by Spencer Carli is the best for beginners that are new to React Native.
如果您不熟悉FlatList,建议您先阅读FlatList的基础知识。 Spencer Carli 撰写的这篇文章最适合于React Native的初学者。
And now, without any further ado, let’s get started and make our searchable FlatList!
现在,事不宜迟,让我们开始制作可搜索的FlatList!
First, let’s set some initial states that we are going to use later in the project:
首先,让我们设置一些初始状态,这些状态将在项目的后面使用:
this.state = {
loading: false,
data: [],
error: null,
};
We’ll also need an array variable:
我们还需要一个数组变量:
this.arrayholder = [];
Apparently an empty list is no fun. So let spice it up with some random list of users.
显然,空列表是没有意思的。 因此,让我们为一些随机的用户列表增添趣味。
We are going to user randomuser.me which is a free, open-source API for generating random user data. Its like Lorem Ipsum, but for people.
我们将访问用户randomuser.me ,这是一个免费的开源 API,用于生成随机用户数据。 它像Lorem Ipsum一样,但对人而言。
Let’s create a function that goes and fetches some user data for us.
让我们创建一个函数,该函数可以为我们获取一些用户数据。
makeRemoteRequest = () => {
const url = `https://randomuser.me/api/?&results=20`;
this.setState({ loading: true });
fetch(url)
.then(res => res.json())
.then(res => {
this.setState({
data: res.results,
error: res.error || null,
loading: false,
});
this.arrayholder = res.results;
})
.catch(error => {
this.setState({ error, loading: false });
});
};
In the above code snippet, we are using the fetch API to make a remote API request. When the request is complete, we will receive the user data which is saved to data state and also to our arrayholder.
在上面的代码片段中,我们使用fetch API发出远程API请求。 请求完成后,我们将接收用户数据,该数据将保存到data状态以及arrayholder 。
Now, for the user to search the list, we need to add a search bar on the top of the FlatList. FlatList has a prop to add any custom component to its heade,r which is useful as we’ll be adding a search component there.
现在,为了让用户搜索列表,我们需要在FlatList的顶部添加一个搜索栏。 FlatList有一个道具可以在其FlatList中添加任何自定义组件,这非常有用,因为我们将在其中添加搜索组件。
renderHeader = () => {
return (
<SearchBar
placeholder="Type Here..."
lightTheme
round
onChangeText={text => this.searchFilterFunction(text)}
autoCorrect={false}
/>
);
};
In the above function we are using react-native-elements SearchBar component as out header component.
在上面的函数中,我们使用react-native-elements SearchBar组件作为out标头组件。
By default, there is no logic which will filter the list as we type inside the SearchBar. For that we’ll need to write a function that will filter the results as the text inside the SearchBar changes.
默认情况下,当我们在SearchBar键入内容时,没有逻辑会过滤列表。 为此,我们需要编写一个函数,该函数将在SearchBar内的文本更改时过滤结果。
searchFilterFunction = text => {
const newData = this.arrayholder.filter(item => {
const itemData = `${item.name.title.toUpperCase()}
${item.name.first.toUpperCase()} ${item.name.last.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
this.setState({ data: newData });
};
The above function will run the filter function on the arrayholder. We’ll be filtering users based on their name, so we’ll store the name inside the itemData variable and convert it to uppercase.
上面的函数将在arrayholder上运行filter函数。 我们将根据用户名过滤用户,因此将名称存储在itemData变量中并将其转换为大写。
This function will receive the text that the user types as a parameter, which we will store in another variable textData after converting it to uppercase.
此函数将接收用户键入的文本作为参数,在将其转换为大写字母后,我们会将其存储在另一个变量textData中。
After that, we’ll use the indexOf to compare both the text and return true if the text is found inside the itemData. If a true is returned, than filter will keep that data other wise ignore it. So new data is returned anytime the user types any text in the search bar. This new data is then set to the data state, which will eventually be used as a data source for FlatList.
之后,我们将使用indexOf比较两个文本,如果在itemData找到了文本,则返回true。 如果返回true,则filter将以其他方式保留该数据,否则将其忽略。 因此,只要用户在搜索栏中键入任何文本,便会返回新数据。 然后,将此新数据设置为data状态,该状态最终将用作FlatList的数据源。
Now its time to render the FlatList.
现在该渲染FlatList了。
<List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
<FlatList
data={this.state.data}
renderItem={({ item }) => (
<ListItem
roundAvatar
title={`${item.name.first} ${item.name.last}`}
subtitle={item.email}
avatar={{ uri: item.picture.thumbnail }}
containerStyle={{ borderBottomWidth: 0 }}
/>
)}
keyExtractor={item => item.email}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
/>
</List>
That is all we need to do. Hurray!!
这就是我们需要做的。 欢呼!!
总结思想 (Closing Thoughts)
I’ve skipped some code that is not so important for this tutorial and for the sake of brevity. You can find the full working repo on GitHub.
为了简洁起见,我跳过了一些对本教程来说并不重要的代码。 你可以找到完整的工作回购 GitHub上。
Also, I believe there can be other ways to achieve the same — so if you do find another way, then please feel free to share it.
另外,我相信还有其他方法可以达到相同目的-因此,如果您确实找到另一种方法,请随时分享。
You can also follow me on Twitter and GitHub. And check out my previous articles in Medium.
您也可以在Twitter和GitHub上关注我。 并查看我以前在Medium中的文章。
Other Helpful Articles:
其他有用的文章:
更多推荐


所有评论(0)