【发布时间】:2020-11-12 09:46:29
【问题描述】:
我想做的是从 API 获取员工列表,将它们保存在状态中并按员工姓名进行“实时”搜索。
我挣扎的地方是我无法使用过滤后的数组更新我的状态。当我开始在搜索字段中输入时,员工会进行过滤,但是一旦我删除了一些字母,就没有任何变化。
如果我 .map() 不是状态,而是包含过滤数组的变量,则一切正常。这在某种程度上与状态和状态更新有关。
这是我的代码:
import "./App.css";
import React, { useState, useEffect } from "react";
import styled from "styled-components";
const Container = styled.div`
width: 1280px;
max-width: 100%;
margin: 0 auto;
th {
text-align: left;
padding: 10px;
background: #f5f5f5;
cursor: pointer;
:hover {
background: #ddd;
}
}
td {
border-bottom: 1px solid #f5f5f5;
padding: 5px;
}
`;
const TopHeader = styled.div`
display: flex;
justify-content: space-between;
padding: 20px;
input {
width: 400px;
padding: 10px;
}
`;
function App() {
const [employees, updateEmployees] = useState([]);
if (employees == 0) {
document.title = "Loading...";
}
useEffect(() => {
fetch("http://dummy.restapiexample.com/api/v1/employees")
.then(res => res.json())
.then(result => {
updateEmployees(result.data);
document.title = `Total: ${result.data.length} `;
});
}, []);
const [searchValue, updateSearch] = useState("");
const filteredEmpl = employees.filter(empl => {
return empl.employee_name.toLowerCase().includes(searchValue.toLowerCase());
});
const handleSearch = e => {
updateSearch(e.target.value);
updateEmployees(filteredEmpl);
};
return (
<Container>
<TopHeader>
<div>
Total employees: <strong>{employees.length}</strong> Filtered
employees: <strong>{filteredEmpl.length}</strong>
</div>
<div>
<input
type="text"
onChange={handleSearch}
value={searchValue}
placeholder="search"
/>
</div>
</TopHeader>
<table style={{ width: "100%" }}>
<thead>
<tr>
<th>id</th>
<th>Employee name</th>
<th>Employee salary</th>
<th>Employee age</th>
</tr>
</thead>
<tbody>
{employees.map(employee => (
<tr key={employee.id}>
<td>{employee.id}</td>
<td>{employee.employee_name}</td>
<td>{employee.employee_salary}</td>
<td>{employee.employee_age}</td>
</tr>
))}
</tbody>
</table>
</Container>
);
}
export default App;
任何想法缺少什么?
【问题讨论】:
-
你能把
const [searchValue, updateSearch] = useState("");和其他useState放在第一行并判断它是否有效吗?你也可以做一个sandbox,这样可以帮助我们更轻松地调试吗? -
updateEmployees(filteredEmpl);- 如果您删除搜索查询,它应该在哪里找到原始员工集?您可能希望为过滤后的员工保留单独的状态,或useMemo。
标签: javascript reactjs react-hooks state