[英]reactJS How can I add a search filter for data from the db
I'm trying to add a search input to filter the data I receive from the database. 我正在尝试添加搜索输入以过滤从数据库接收到的数据。 Could anybody walk me through how I can go about filtering and displaying on the results that are searched.
谁能指导我逐步介绍如何过滤和显示搜索结果。 I want to search for the MeetingName that was mapped from items.
我想搜索从项目映射的MeetingName。 Right now the app is displaying the entire list of items from the database.
现在,该应用程序正在显示数据库中项目的完整列表。
Thanks. 谢谢。
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);
You need to change few things in your component 您需要更改组件中的一些内容
Initialise state in constructor as below 在构造函数中初始化状态如下
this.state = { searchedValue: '' };
Add an onChange event listener on input
在
input
上添加onChange事件侦听input
<input type="text" placeholder="search" onChange={this.onSearch} value={this.state.searchedValue} />
Change the state with typed value when onSearch
function is called 调用
onSearch
函数时,使用键入的值更改状态
onSearch = (event) => { this.setState({ searchedValue: event.target.value }); }
Filter the items
list with the searchedValue in render
function 在
render
函数中使用searchedValue过滤items
列表
const filteredItems = items.filter((item) => item.meetingName.includes(this.state.searchedValue));
Use the filteredItems
array to create multiple tr
使用
filteredItems
数组创建多个tr
As stated in the comment on your post, react-data-grid is a nice option but you can choose what fits best for your application 如您对帖子的评论所述, react-data-grid是一个不错的选择,但是您可以选择最适合您的应用程序的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.