我正在实现一个带有搜索过滤器的react数据表来搜索行。您可以在此处查看 UI ,以便更好地理解代码。我实现了它最初按名称搜索行。(稍后我将实现它以在所有列中搜索)。
正如您在 UI 中看到的,顶部有三个条目,分别名为“Kamakshi”、“Kanika”和“Kanika”。当我在搜索框中键入“Kam”时,就会显示此结果。现在按下退格键,我的输入变成了“ka”,这意味着我的搜索结果应该显示三行“Kamakshi”、“Kanika”和“Kanika”。但是没有任何变化。
每次输入发生变化时,我都想触发搜索过滤器。我将它作为 useEffect 中的依赖项传递,但没有奏效。
这是我的Bookings2.js(表在此实现)
import React, {useState, useEffect} from 'react';
import axios from 'axios';
import {Link} from 'react-router-dom';
import '../../static/Bookings.css';
import {BsFilterRight} from "react-icons/bs";
let bookings_array = [];
const Bookings2= ()=>{
const[Bookings, setBooking]=useState([]);
const[search, setSearch]=useState("");
useEffect(()=>{
loadUsers();
}, []);
useEffect(()=>{
if(search.length){
setBooking(
Bookings.filter(Booking =>
Booking.name.toLowerCase().includes(search.toLowerCase())
)
)
}else{
setBooking(bookings_array)
}
}, [search, Bookings]);
const loadUsers= async()=>{
const result =await axios.get("http://localhost:3001/Bookings");
bookings_array=result.data.reverse();
setBooking(bookings_array);
};
const deleteUser=async id => {
await axios.delete(`http://localhost:3001/Bookings/${id}`);
loadUsers();
}
return(
<div className="Booking-page-container">
<h2 className="text-center mb-4">Bookings2 Page</h2>
<table class="table table-bordered table-striped border shadow">
<thead>
<tr>
<th scope="col" colSpan={5}>
<BsFilterRight/>
<input
placeholder=" search....."
onChange={e=>setSearch(e.target.value)}
/>
</th>
</tr>
</thead>
<thead class="thead-dark">
<tr>
<th scope="col"></th>
<th scope="col">Name</th>
<th scope="col">Consultant</th>
<th scope="col">Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{Bookings.map((Booking,index)=>(
<tr>
<th scope="row">{index+1}</th>
<td>{Booking.name}</td>
<td>{Booking.consultant}</td>
<td>{Booking.email}</td>
<td>
<Link class="btn btn-primary mr-2" to={`/Bookings/view/${Booking.id}`}>View</Link>
<Link class="btn btn-outline-primary mr-2" to={`/Bookings/edit/${Booking.id}`}>Edit</Link>
<Link class="btn btn-danger" onClick={()=>deleteUser(Booking.id)}>Delete</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default Bookings2;