reactJS如何为数据库中的数据添加搜索过滤器

时间:2018-07-15 10:44:57

标签: javascript reactjs

我正在尝试添加搜索输入以过滤从数据库接收到的数据。 谁能指导我逐步介绍如何过滤和显示搜索结果。我想搜索从项目映射的MeetingName。现在,该应用程序正在显示数据库中项目的整个列表。

谢谢。

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)}
                            >
                                &times;
                            </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);

1 个答案:

答案 0 :(得分:1)

您需要更改组件中的一些内容

  1. 构造函数中的初始化状态如下

    this.state = { searchedValue: '' };
    
  2. input

    上添加onChange事件侦听器
    <input type="text" placeholder="search" onChange={this.onSearch} value={this.state.searchedValue} />
    
  3. 在调用onSearch函数时使用键入的值更改状态

    onSearch = (event) => {
        this.setState({ searchedValue: event.target.value });
    }
    
  4. 使用items函数中的searchedValue过滤render列表

    const filteredItems = items.filter((item) => item.meetingName.includes(this.state.searchedValue));
    
  5. 使用filteredItems数组创建多个tr

如您的帖子评论中所述,react-data-grid是一个不错的选择,但您可以选择最适合您的应用的