首页 > 解决方案 > 如何使用 React 对相同的表数据进行过滤和排序?

问题描述

我有一个问题,在加载页面时,我可以按“名称”列(升序或降序)对表格进行排序 - - 或者 - - 使用搜索栏过滤员工的姓名。我的问题是,一旦我按字母顺序排序,搜索/过滤器就不再起作用了。

我对 React 很陌生(我确信这在我的代码中非常明显)所以如果有什么明显的我做错了,请告诉我。提前致谢!

import React, { Component } from "react";
import API from "../utils/API"
import EmployeeRow from "./EmployeeRow"

class TableMain extends Component {
    state = {
        result: [],
        search: "",
        sortOrder: "descending"
    }

    componentDidMount() {
        API.search()
            .then(results => {
                console.log(results)
                this.setState({
                    result: results.data.results.map((res, i) => ({
                        image: res.picture.large,
                        firstName: res.name.first,
                        lastName: res.name.last,
                        phone: res.phone,
                        email: res.email,
                        dob: res.dob.date,
                        key: i
                    })
                    )
                })
            })
    };

    filterResults = (results) => {
        const value = this.state.search
        const finalResult = results.filter((employee) => {
            const lastName = employee.lastName.toLowerCase();
            const firstName = employee.firstName.toLowerCase()
            const fullName = firstName + " " + lastName

            if (fullName.includes(value)) {
                return employee
            }
        });

        return finalResult
    };

    sortResults = (event) => {
        const results = this.state.result
        // const id = event.target.id
        // if (id === 'name'){
        // } else if (id === 'phone'){
        // } else if (id === 'email'){
        // }
        if (this.state.sortOrder === "descending") {
            results.sort((a, b) => {
                if (a.firstName > b.firstName) {
                    return -1
                }
                return a.firstName > b.firstName ? 1 : 0
            }, 
            this.setState({ sortOrder: "ascending" }))
        } else if (this.state.sortOrder === "ascending") {
            results.sort((a, b) => {
                if (a.firstName < b.firstName) {
                    return -1
                }
                return a.firstName > b.firstName ? 1 : 0
            }, 
            this.setState({ sortOrder: "descending" }))
        }

        console.log("RESULTS: ", results)

        this.setState({
            sortedResults: results,
            isSorted: true
        })
    }

    onChange = e => {
        const value = e.target.value;
        if (!value) {
            this.setState({ isSearchEmpty: true });
        } else {
            this.setState({ search: e.target.value, isSearchEmpty: false });
        }
    }

    render() {
        // console.log("State", this.state)
        let employeeResults = this.state.result 

        if (this.state.isSearchEmpty) {
            employeeResults = this.state.result
        } else {
            employeeResults = this.filterResults(this.state.result)
        }

        if (this.state.isSorted) {
            employeeResults = this.state.sortedResults
        }

        return (
            <div>
                <input label="Search" onChange={this.onChange} />
                <div className="row">
                    <table style={{ width: "100%" }}>
                        <tbody>
                            <tr>
                                <th>Image</th>
                                <th style={{ cursor: "pointer" }} onClick={this.sortResults} id="name">Name</th>
                                <th id="phone">Phone</th>
                                <th id="email">Email</th>
                                <th id="dob">DOB</th>
                            </tr>
                            {[...employeeResults].map((item) =>
                                <EmployeeRow
                                    image={item.image}
                                    firstName={item.firstName}
                                    lastName={item.lastName}
                                    email={item.email}
                                    phone={item.phone}
                                    dob={item.dob}
                                    key={item.key}
                                />
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        )}
}


export default TableMain;

标签: javascriptreactjssortingfilterstate

解决方案


问题是:

    if (this.state.isSorted) {
      employeeResults = this.state.sortedResults;
    }

排序时,您设置state.isSorted为 true,但是一旦完成,您就永远不会将其设置回 false。然后,当您尝试过滤时,请执行过滤器:

    if (this.state.isSearchEmpty) {
      employeeResults = this.state.result;
    } else {
      employeeResults = this.filterResults(this.state.result);
    }

    if (this.state.isSorted) { // this is never reset after sorting.
      employeeResults = this.state.sortedResults;
    }

this.state.isSorted仍然如此,您this.state.sortedResults再次使用这些值。


如果有明显的我做错了,请告诉我

当您过滤/排序相同的数据集合时,您自己会变得很棘手。这就是您需要在渲染中执行操作的原因,因为您正在尝试维护原始列表以供以后使用。

如果您将列表分为两个集合:未修改的原始列表和显示列表,您始终可以参考原始列表进行过滤/排序。

  componentDidMount() {
    API.search().then(results => {
      const tableData = results.data.results.map((res, i) => ({
        image: res.picture.large,
        firstName: res.name.first,
        lastName: res.name.last,
        phone: res.phone,
        email: res.email,
        dob: res.dob.date,
        key: i
      }));

      this.setState({ originalResults: tableData, displayResults: tableData });
    });
  }

然后过滤可以完成,一旦onChange发生:

  onChange = e => {
    const query = e.target.value;

    this.setState(prevState => ({
      displayResults:
        query.length > 0
          ? this.filterResults(query, prevState.originalResults)
          : prevState.originalResults
    }));
  };

同样对于排序,可以在显示结果而不是整体上执行,这意味着您现在可以对过滤结果进行排序。

我在这里创建了一个示例https://codesandbox.io/s/sad-cannon-d61z6

我删除了所有缺失的功能。


推荐阅读