javascript - reactJS 如何为数据库中的数据添加搜索过滤器
问题描述
我正在尝试添加一个搜索输入来过滤我从数据库收到的数据。任何人都可以告诉我如何在搜索结果上进行过滤和显示。我想搜索从项目映射的会议名称。现在,该应用程序正在显示数据库中的整个项目列表。
谢谢。
import React, { Component } from 'react';
import { Table, Input } from 'reactstrap';
import { connect } from 'react-redux';
import { getItems, deleteItem } from "../actions/itemActions";
import PropTypes from 'prop-types';
class Directory extends Component {
componentDidMount() {
this.props.getItems();
}
onDeleteClick = (id) => {
this.props.deleteItem(id);
}
render() {
const { items } = this.props.item;
return(
<div>
<Input type="text" placeholder="search"/>
<br/>
<Table>
<thead>
<tr>
<th>Day</th><th>Time</th><th>Meeting Name</th><th>Address</th><th>City</th><th>Zip Code</th><th></th>
</tr>
</thead>
{items.map(({ _id, Day, Time, MeetingName, Address, City, Zip }) => (
<tbody key={_id}>
<tr>
<td>{Day}</td><td>{Time}</td><td>{MeetingName}</td><td>{Address}</td><td>{City}</td><td>{Zip}</td>
{/*<Button
className="remove-btn"
color="danger"
size="sm"
onClick={this.onDeleteClick.bind(this, _id)}
>
×
</Button>*/}
</tr>
</tbody>
))}
</Table>
</div>
);
}
}
Directory.propTypes = {
getItems: PropTypes.func.isRequired,
item: PropTypes.object.isRequired
}
const mapStateToProps = (state) => ({
item: state.item
})
export default connect(
mapStateToProps,
{ getItems, deleteItem }
)(Directory);
解决方案
您需要更改组件中的一些内容
在构造函数中初始化状态如下
this.state = { searchedValue: '' };
添加 onChange 事件监听器
input
<input type="text" placeholder="search" onChange={this.onSearch} value={this.state.searchedValue} />
onSearch
调用函数时使用类型值更改状态onSearch = (event) => { this.setState({ searchedValue: event.target.value }); }
在函数
items
中使用 searchedValue过滤列表render
const filteredItems = items.filter((item) => item.meetingName.includes(this.state.searchedValue));
使用
filteredItems
数组创建多个tr
如您帖子的评论中所述,react-data-grid是一个不错的选择,但您可以选择最适合您的应用程序的选项
推荐阅读
- c# - Visual Studio for Mac 不允许我创建新的表单项目
- reactjs - 我列出了我的关键道具,但仍然收到以下错误:列表中的每个孩子都应该有一个唯一的“关键”道具
- prestashop - WebServices 更新是否有任何默认触发器(挂钩)?
- javascript - 我尝试在 p5.js 中保存 27 张图片,但只有 10 张保存到我的下载文件夹中。为什么所有文件都没有保存?
- jboss - 如何在 JBoss 7.1.1 中使用 MySQL8.0.19?
- node.js - 我应该使用的最大查询参数 url 是多少?
- python - 同一个numpy数组中的不同十进制格式
- facebook - 如何在 vuejs + django rest 框架项目中正确执行“使用 facebook 登录”?
- react-native - 在 React Native 中更改 Expo 图标
- ggplot2 - 如何设置分面时显示的y轴值的数量