如何在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={???},使结果只显示所选状态和键入的关键字。

您可以根据集合的节点值进行数组搜索,如以下

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

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

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

最新更新