使用筛选功能搜索数据不起作用



我在呈现过滤器函数时遇到问题。我认为问题是我不会回smth,但我不太确定。我使用react和json文件来显示数据。这是我在控制台上收到的警告"js:117警告:列表中的每个子级都应该有一个唯一的";键";道具

检查SearchTable的渲染方法。看见https://reactjs.org/link/warning-keys了解更多信息。在tr〃;

代码:

import data from "../data.json";
const SearchTable = () => {
const [searchTerm, setSearchTerm] = useState("");
return (
<div className="container">
<input 
type="text"
placeholder="Search..." 
className="form-control" 
style ={{marginTop:50 ,marginBottom: 20, width : "40%"}} 
onChange= {(e)=>{
setSearchTerm(e.target.value); 
}}
/>
<table className="table table-bordered">
<thead className="thead-dark">
<tr>
<th>Number</th>
<th>PartitionId</th>
<th>enqueueTime</th>
</tr>
</thead>
<tbody>
{data.filter((val) => {
if(searchTerm === ""){
return val;
} 
else if (
val.partitionId === searchTerm ||
val.enqueueTime === searchTerm

) {
console.log("hej")
return val;

}
}).map((m) => (
<tr key={m.id}>
<td>{m.Nr}</td>
<td>{m.partitionId}</td>
<td>{m.enqueueTime}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default SearchTable;```

如果我是你,我会从模板中删除业务逻辑。更重要的是,如果一个条目应该放在已筛选的数组中,那么传递给filter方法的函数应该返回true,否则应该返回false。我在代码下面放了一个通用的过滤器函数。还有一件事,如果字符串为空,就没有理由对数组调用过滤器。如果你不想过滤,如果不需要,就不要使用CPU;(

PS。在呈现项目时使用了不存在的对象键。将其更改为Nr或partitionId。

PPS。我们应该将搜索到的字符串更改为小写,数据对象中的条目也是如此。

干杯!如果你有任何问题,我很乐意回答。

import data from "../data.json";
import React, { useState, useEffect } from 'react';
const SearchTable = () => {
const [searchTerm, setSearchTerm] = useState("");
const [filteredData, setFilteredData] = useState(data);

const filterData = () => {
if (searchTerm === '') {
setFilteredData(data);
return;
}

setFilteredData(data.filter(entry => {
return Object.keys(entry).some(entryKey => {
const entryValue = entry[entryKey].toString().toLocaleLowerCase();

return entryValue.contains(searchTerm);
})
}));
};

useEffect(filterData, [searchTerm]);
return (
<div className="container">
<input 
type="text"
placeholder="Search..." 
className="form-control" 
style ={{marginTop:50 ,marginBottom: 20, width : "40%"}} 
onChange= {(e)=>{
setSearchTerm(e.target.value.toLocaleLowerCase()); 
}}
/>
<table className="table table-bordered">
<thead className="thead-dark">
<tr>
<th>Number</th>
<th>PartitionId</th>
<th>enqueueTime</th>
</tr>
</thead>
<tbody>
{filteredData.map((m) => (
<tr key={m.Nr}>
<td>{m.Nr}</td>
<td>{m.partitionId}</td>
<td>{m.enqueueTime}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default SearchTable;

最新更新