我的React Pagination工作得很好,但搜索功能不是吗?

时间:2018-05-10 02:42:21

标签: javascript reactjs express pagination

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

IssueList.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页)。

1 个答案:

答案 0 :(得分: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;