javascript - 我的 React Pagination 工作得很好,但搜索功能却不行?

标签 javascript reactjs express pagination

我已经实现了 React 应用程序,使用 Express Server 从 MongoDB 获取数据库。 分页功能运行良好,但当我实现搜索功能时,仅在输入框中键入内容时才起作用。如果我删除该字符,它应该再次搜索,但它仍然存在。 有人可以帮忙验证我的代码吗?

问题列表.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import 'whatwg-fetch';
import Pagination from '../components/Pagination';
import IssueAdd from '../components/IssueAdd';

class IssueList extends Component {

  constructor(props) {
    super(props);


    this.state = {
        issues: [],
        pageOfItems: [],
    };


    this.createIssue = this.createIssue.bind(this);
    this.onChangePage = this.onChangePage.bind(this);
    this.filterList = this.filterList.bind(this);
  }
  componentDidMount() {
        this.loadData();
  }

  loadData() {
    fetch('/api/issues').then(response => {
      if (response.ok) {
        response.json().then(data => {
          data.records.forEach(issue => {
            issue.created = new Date(issue.created);
            if (issue.completionDate) {
              issue.completionDate = new Date(issue.completionDate);
            }
          });
          this.setState({ issues: data.records });
        });
      } else {
        response.json().then(error => {
          alert(`Failed to fetch issues ${error.message}`);
        });
      }
    }).catch(err => {
      alert(`Error in fetching data from server: ${err}`);
    });
  }

  onChangePage(pageOfItems) {
    this.setState({ pageOfItems: pageOfItems });
  }

  filterList = (e) => {
    var updatedList = this.state.issues;
    updatedList = updatedList.filter((item) => {
        return item.title.toLowerCase().search(e.target.value.toLowerCase()) !== -1;
    });
    this.setState({ issues: updatedList });
  }

  render() {
    return (
      <div>
        <h1>Issue Tracker</h1>
        <hr />
        <div className="filter-list">
            <form>
                <fieldset className="form-group">
                    <legend>Search</legend>
                    <input 
                        type="text" 
                        className="form-control form-control-lg" 
                        placeholder="Search" 
                        onChange={this.filterList}
                    />
                </fieldset>
            </form>
        </div>
        <div className="panel panel-default">
                <table className="table table-bordered">
                <thead>
                    <tr>
                    <th>ID</th>
                    <th>Status</th>
                    <th>Owner</th>
                    <th>Created</th>
                    <th>Effort</th>
                    <th>Completion Date</th>
                    <th>Title</th>
                    </tr>
                </thead>
                    <tbody>
                    {this.state.pageOfItems.map(issue => (
                        <tr key={issue._id}>
                                <td>{issue._id}</td>
                                <td>{issue.status}</td>
                                <td>{issue.owner}</td>
                                <td>{issue.created.toDateString()}</td>
                                <td>{issue.effort}</td>
                                <td>{issue.completionDate ? issue.completionDate.toDateString() : ''}</td>
                                <td>{issue.title}</td>
                              </tr>
                            ))}
                    </tbody>
                </table>
            </div>
        <Pagination
            items={this.state.issues}
            onChangePage={this.onChangePage}
        />
        <hr />
        <IssueAdd createIssue={this.createIssue} />
      </div>
    );
  }
}

export default IssueList;
<小时/>

已编辑

我尝试将 loadData() 函数添加到 filterList()

filterList = (e) => {
    this.loadData();
    var updatedList = this.state.issues;
    updatedList = updatedList.filter((item) => {
        return item.title.toLowerCase().search(e.target.value.toLowerCase()) !== -1;
    });
    this.setState({ issues: updatedList });
  }

它可以搜索,但之后它会返回到初始状态(第 1 页)。

最佳答案

您需要将 value 参数添加到您的输入中以控制其值。这可能是你的问题。我对此进行了更新,包括在保存未过滤数组的状态下添加一个持有者。

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import 'whatwg-fetch';
import Pagination from '../components/Pagination';
import IssueAdd from '../components/IssueAdd';

class IssueList extends Component {

  constructor(props) {
    super(props);


    this.state = {
        issues: [],
        holder: [],
        pageOfItems: [],
    };


    this.createIssue = this.createIssue.bind(this);
    this.onChangePage = this.onChangePage.bind(this);
    this.filterList = this.filterList.bind(this);
  }
  componentDidMount() {
        this.loadData();
  }

  loadData() {
    fetch('/api/issues').then(response => {
      if (response.ok) {
        response.json().then(data => {
          data.records.forEach(issue => {
            issue.created = new Date(issue.created);
            if (issue.completionDate) {
              issue.completionDate = new Date(issue.completionDate);
            }
          });
          this.setState({ issues: data.records, holder: data.records });
        });
      } else {
        response.json().then(error => {
          alert(`Failed to fetch issues ${error.message}`);
        });
      }
    }).catch(err => {
      alert(`Error in fetching data from server: ${err}`);
    });
  }

  onChangePage(pageOfItems) {
    this.setState({ pageOfItems: pageOfItems });
  }

  filterList = (e) => {
    let { value } = e.target
    this.setState({ value }, () => {
    //running this after setting the value in state because of async
    var updatedList = this.state.holder;
    updatedList = updatedList.filter((item) => {
        return item.title.toLowerCase().search(this.state.value.toLowerCase()) !== -1;
    });
    this.setState({ issues: updatedList });
    })
  }

  render() {
    return (
      <div>
        <h1>Issue Tracker</h1>
        <hr />
        <div className="filter-list">
            <form>
                <fieldset className="form-group">
                    <legend>Search</legend>
                    <input 
                        type="text" 
                        className="form-control form-control-lg" 
                        placeholder="Search" 
                        value={this.state.value}
                        onChange={this.filterList}
                    />
                </fieldset>
            </form>
        </div>
        <div className="panel panel-default">
                <table className="table table-bordered">
                <thead>
                    <tr>
                    <th>ID</th>
                    <th>Status</th>
                    <th>Owner</th>
                    <th>Created</th>
                    <th>Effort</th>
                    <th>Completion Date</th>
                    <th>Title</th>
                    </tr>
                </thead>
                    <tbody>
                    {this.state.pageOfItems.map(issue => (
                        <tr key={issue._id}>
                                <td>{issue._id}</td>
                                <td>{issue.status}</td>
                                <td>{issue.owner}</td>
                                <td>{issue.created.toDateString()}</td>
                                <td>{issue.effort}</td>
                                <td>{issue.completionDate ? issue.completionDate.toDateString() : ''}</td>
                                <td>{issue.title}</td>
                              </tr>
                            ))}
                    </tbody>
                </table>
            </div>
        <Pagination
            items={this.state.issues}
            onChangePage={this.onChangePage}
        />
        <hr />
        <IssueAdd createIssue={this.createIssue} />
      </div>
    );
  }
}

export default IssueList;

关于javascript - 我的 React Pagination 工作得很好,但搜索功能却不行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50264702/

相关文章:

javascript - 如何在 React 中创建可过滤表

node.js - 使用 passport.js 和 express.js (node.js) 制作安全的 oauth API

javascript - 获取_.groupBy的值

javascript - 对选项值进行 ASC 排序

javascript - 将 redux-saga 与 ES6 生成器结合使用与 redux-thunk 与 ES2017 async/await 结合使用的优缺点

javascript - ReactJS:动态添加标签和内容到 react-dom 并重新加载它

node.js - NodeJS : Mongoose return wrong results from MongoDB although Mongo shell return correct ones

node.js - Mongoose :.findById 不是函数

javascript - 在php/javascript中单击另一个页面中的按钮时需要启用按钮

javascript - document.body.innerHTML 杀死事件需要替代解决方案