首页 > 解决方案 > 如何使用过滤器按钮过滤 React 中的搜索结果?

问题描述

如何使用 react 和 firebase 过滤搜索结果?

我的这段代码工作正常,每次我输入一个字母都会显示我的 firebase 数据搜索结果

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import './App.css';
import firebase from './Firebase';


class App extends Component {
  constructor(props) {
    super(props);
    this.ref = firebase.firestore().collection('Products');
    this.unsubscribe = null;
    this.state = {
      filter: "",
      Products: []
    };
  }

  onCollectionUpdate = (querySnapshot) => {
    const Products = [];
    querySnapshot.forEach((doc) => {
      const { title, status } = doc.data();
      Products.push({
        key: doc.id,
        doc, // DocumentSnapshot
        title,
        status
      });
    });
    this.setState({
      Products
   });
  }

  handleChange = event => {
    this.setState({ filter: event.target.value });
  };

  componentDidMount() {
    this.unsubscribe = this.ref.onSnapshot(this.onCollectionUpdate);
  }

  render() {
    const { filter, Products } = this.state;
    const lowercasedFilter = filter.toLowerCase();
    const filteredData = Products.filter(item => {
      return Object.keys(item).some(key =>
        typeof item[key] === "string" && item[key].toLowerCase().includes(lowercasedFilter)
      );
    });

    return (
      <div class="container">
        <div class="panel panel-default">

          <input value={filter} onChange={this.handleChange} placeholder="Search Book"/>
          <div class="panel-body">
            <table class="table table-stripe">
              <thead>
                <tr>
                  <th>Title</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {filteredData.map(item => (
                  <tr>
                    <td><Link to={`/show/${item.key}`}>{item.title}</Link></td>
                    <td>{item.status}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

        </div>
      </div>
    );
  }
}

export default App;

但现在我想添加另一个过滤器,专门根据我的 firebase 的状态过滤这本书{Product.status}

像这样的东西,

<input value={filter} onChange={this.handleChange} placeholder="Search Book"/>
<select className="ml-2 mb-2">
 {this.state.Products.map(Products => (
  <option onClick={???}>{Products.status}</option>
 ))};
</select>

我该怎么做??我应该在这里写什么onClick={???}以使结果仅显示所选状态和键入的关键字。

标签: reactjsfirebasegoogle-cloud-firestore

解决方案


您可以像这样根据集合的节点值进行数组搜索

const thfilteredData = firebase_data.filter(({name}) => {
name = name.toLowerCase();
       return name.includes(value.toLowerCase());
   });
setFiltredRestaurants(thfilteredData);

我已经使用名称来匹配子节点的名称值。您可以将其放在搜索输入的 onChange 上,或者对于 onClick,您可以创建一个函数并传递选项值以进行匹配。在您的情况下,这可能如下所示。

filterProducts = (status) => {
    const thfilteredData = Products.filter(({productstatus}) => productstatus === status);
    this.setState({
        filteredData: thfilteredData
    });
}

推荐阅读