javascript - 如何使用 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;
解决方案
问题是:
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
我删除了所有缺失的功能。
推荐阅读
- apache-flink - 流模拟过程中缺乏再现性
- r - model_matrix() 到底是做什么的?
- reactjs - 如何在功能组件中使用 setNativeProps?反应原生
- python - 如何在不丢失 dt 方法功能的情况下从 pandas 的“日期时间”列中删除时间?
- java - 将 CSV 直接加载到对象集合中
通过 Java 流 API - android - 升级到 android studio 4.0 后未解决的数据绑定参考
- discord.js - 我如何将角色与用户进行比较或查看给定的所需角色是否是他们的最高角色?
- arrays - 在 React 中,如何在列表中找到符合某些条件的第一项?
- c# - EF Core:发送到数据库的重复值
- c# - 如何从 JSON 中读取列表