reactjs - 如何使用过滤器按钮过滤 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);
我已经使用名称来匹配子节点的名称值。您可以将其放在搜索输入的 onChange 上,或者对于 onClick,您可以创建一个函数并传递选项值以进行匹配。在您的情况下,这可能如下所示。
filterProducts = (status) => {
const thfilteredData = Products.filter(({productstatus}) => productstatus === status);
this.setState({
filteredData: thfilteredData
});
}
推荐阅读
- excel - 在 Excel 公式中将列号与行字母分开
- python - Pandas 使用数据框名称替换第二个数据框中任何位置的数据,并带有 id
- python-3.x - Python:将文件树复制到文本文件
- mysql-workbench - 无法使用本地套接字/管道 MAMP 连接到 MySQL
- ios - 允许用户在 React Native 中更改 App 图标
- mysql - MySQL:在有限范围内删除单个选定行
- vagrant - 无法在 PATH 模式 040777 中解析不安全的世界可写目录 /mnt/c
- amazon-web-services - ec2 上没有更多磁盘空间
- mongodb - 在 MongoDB 中的记录中取消嵌套值
- bash - 使用 awk 或 bash 将字符串附加到列中单元格的所有元素