首页 > 解决方案 > 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)}
                            >
                                &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);

标签: javascriptreactjs

解决方案


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

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

    this.state = { searchedValue: '' };
    
  2. 添加 onChange 事件监听器input

    <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是一个不错的选择,但您可以选择最适合您的应用程序的选项


推荐阅读