繁体   English   中英

React Native Firebase 搜索列表视图

[英]React Native Firebase search listview

我的 React Native 应用程序中有一个来自 Firebase 的列表视图。 我遇到了一些关于人们如何使用 fetch 函数搜索列表视图的教程,但对 Firebase 没有任何帮助。

我的列表视图的标题处有一个搜索栏,如何使用 Firebase 按关键字搜索并过滤结果?

我按照 Firebase 网站上的指南来设置我的列表视图和数据源。 我希望能够在每个字段中按关键字进行搜索

listenForItems(itemsRef) {

itemsRef.on('value', (snap) => {

  var items = [];
  snap.forEach((child) => {
    items.push({
      title: child.val().title,
      category: child.val().category,
      description: child.val().description,
    });
  });

  this.setState({
    dataSource: this.state.dataSource.cloneWithRows(items)
  });

});
}

我终于想通了这一点。 此代码基于特定的项目名称进行搜索。

数据库

 {
  "directory" : {
    "macintosh" : {
      "address" : "117 East 11th Street, Hays, KS 67601",
      "firstLetter" : "m",
      "title" : "Macintosh",
    },
   "apple" : {
      "address" : "117 East 11th Street, Hays, KS 67601",
      "firstLetter" : "a",
      "title" : "apple",
    },
  },

带搜索栏的列表视图

  render() {
    return (
      <View style={styles.container}>
      <ScrollView>
      <SearchBar
          returnKeyType='search'
          lightTheme
          placeholder='Search...'
          onChangeText={(text) => this.setState({searchText:text})}
          onSubmitEditing={() => this.firstSearch()}
      />
        {
          this.state.loading &&

          <ActivityIndicator
            size="large"
            color="#3498db"
            style={styles.activityStyle}
          />

        }
        <ListView
            dataSource={this.state.dataSource}
            renderRow={this._renderItem.bind(this)}
            enableEmptySections={true}
        />
        </ScrollView>
      </View>
    );
  }

搜索功能

  firstSearch() {
    this.searchDirectory(this.itemsRef);
  }



searchDirectory(itemsRef) {

var searchText = this.state.searchText.toString();

if (searchText == ""){
  this.listenForItems(itemsRef);
}else{
  itemsRef.orderByChild("searchable").startAt(searchText).endAt(searchText).on('value', (snap) => {

    items = [];
    snap.forEach((child) => {
      items.push({
        address: child.val().address,
        firstLetter: child.val().firstLetter,
        title: child.val().title,
      });
    });


    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(items)
    });

  });
}

}

这通过使用 orderbychild.startat().endat() firebase 函数替换 listview 数据源来搜索 firebase。 它是最接近“SELECT * BY %LIKE%”sql 搜索功能的东西。

我修改了我的代码以按第一个字母搜索。 因此,如果有人搜索“Macbuk”,它仍然会显示“Macbook”结果。 它只搜索 M。我在我的数据库中添加了另一个字段到要搜索的标题的第一个字母并将其设为小写。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM