javascript - 需要一个高级搜索过滤器 - React Native
问题描述
我有一个 SearchBar 和一个简单的 FlatList。我的搜索过滤器逻辑工作正常,但对于简单搜索来说很好。
示例:如果我的 FlatList 包含三个项目
- 参观时间。
- 他知道探视时间。
- 参观和小时。
在我的 SearchBar 中,如果我搜索“访问 h”,它只会呈现项目 2 -> 2。他知道访问时间。
我希望它在我搜索“visit h”时呈现所有 3 个项目 我的搜索过滤器应该查找包含“visit”和“h”的每个项目。“访问”中还应包括“访问”
我怎样才能捕获这种类型的过滤器?有没有可以使用的js库?执行此搜索过滤器的任何有效方法?
我当前的代码如下:
export default class HomeComponent extends Component {
constructor(props) {
super(props)
this.state = {
isLoading: true,
notifications: [],
query: '',
temp: []
}
};
componentDidMount() {
fetch('https://140xya6a67.execute-api.ap-southeast-1.amazonaws.com/dev/', {
method: 'GET',
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
notifications: responseJson,
notificationRead: false,
temp: responseJson,
})
})
};
goToDetails() {
return this.props.navigation.navigate(Details);
}
renderItem({item}) {
return <NotificationItem item={item}
onPress={() => {this.goToDetails()}}/>
}
handleSearch(text) {
const newData = _.filter(this.state.temp, (item) => {
const itemData = item.Desc ? item.Desc.toUpperCase() : ''.toUpperCase();
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
this.setState({
notifications: newData,
query: text,
});
}
renderContent() {
let {notifications} = this.state;
return (
<View>
<SearchBar placeholder='type here...' lightTheme round value={this.state.query}
onChangeText={(text) => {this.handleSearch(text)}}/>
<FlatList
keyExtractor={(item, id) => item.id}
data={notifications}
renderItem={this.renderItem.bind(this)}
/>
</View>
);
}
render() {
let {fill, container} = styles;
return (
<View style={[fill, container]}>
{this.renderContent()}
</View>
);
}
}
解决方案
您可以编写自己的简单过滤器,如下所示(未测试):
handleSearch(text) {
if (!text || text.length === 0) {
this.setState({
notifications: this.state.temp,
query: text,
});
return;
}
const newData = _.filter(this.state.temp, item => {
const itemData = item.Desc ? item.Desc.toUpperCase() : ''.toUpperCase();
const textParts = text.toUpperCase().split(' ');
let shouldInclude = true;
for (let i = 0; i < textParts.length; i++) {
const part = textParts[i];
shouldInclude = shouldInclude && (itemData.indexOf(part) > -1);
if (!shouldInclude) {
return false;
}
}
return true;
});
this.setState({
notifications: newData,
query: text,
});
}
推荐阅读
- powershell - 在不访问 ARS 控制台的情况下创建计算机对象
- angular - Angular 9:销毁子组件后向父组件发送数据
- r - 具有双 y 轴的 ggplot 图
- jquery - 在 asp.net core mvc 中使用 Dapper 连接表并按多个条件过滤
- python - 如何在python中使用多维列表
- docker - Traefik 2 docker不显示客户端真实IP
- python - 打开 Apache Tomcat 本地访问日志
- jupyter-notebook - 如何在 jupyter notebook 文本单元格中输入“$”?
- unit-testing - Jest .toBeCalledWith objectContaining 不匹配期望收到
- c++ - 关于派生类和基类函数的问题