问题
I am using react-table as data-grid. I am implementing table based search filtering. The filtering does not seem like working , as a result its returning empty results. I do not where I am going wrong.
Can someone help?
Help would be appreciated
Data format
let data =[ {id: 1, val1: "45GFSDSD", val2: "AKFHFDH83E3HHYE"},
{id: 2, val1: "46FDGDGDGDG", val2: "AKFHFDH83E3HFGD"},
{id: 3, val1: "56FDGGFGF", val2: "AERTFDH83E3HHYD"}
]
Component code
import * as React from 'react';
import ReactTable from 'react-table';
class MyTable extends React.Component {
constructor () {
super();
this.state = {
data: data, // data from API, structure has been shown above
search: ''
}
}
render () {
let data = this.state.data
if (this.state.search)
{
data = data.filter((value) => {
return value.val1.includes(search)||value.val2.includes(search)|| String(value.id).includes(search)
})
}
return (
<div>
Search:
<input value={this.state.search} onChange={e => this.setState({search: e.target.value})} />
<ReactTable data={data} columns={columns} />//column object
</div>
)
}
}
回答1:
You need to have two arrays, one for data from the api and one for filtered data. Your state will be like.
//on first load both arrays will have the same data
state = {
data: [
{ id: 1, val1: "45GFSDSD", val2: "AKFHFDH83E3HHYE" },
{ id: 2, val1: "46FDGDGDGDG", val2: "AKFHFDH83E3HFGD" },
{ id: 3, val1: "56FDGGFGF", val2: "AERTFDH83E3HHYD" }
],
filteredData: [
{ id: 1, val1: "45GFSDSD", val2: "AKFHFDH83E3HHYE" },
{ id: 2, val1: "46FDGDGDGDG", val2: "AKFHFDH83E3HFGD" },
{ id: 3, val1: "56FDGGFGF", val2: "AERTFDH83E3HHYD" }
]
};
Then you'll need a function for filter data, when the text changes in the input
handleSearch = event => {
const search = event.target.value.toLowerCase();
this.setState({
filteredData: this.state.data.filter(
item =>
(item.val1 && item.val1.toLowerCase().includes(search)) ||
(item.val2 && item.val2.toLowerCase().includes(search))
)
});
};
Your input
<input
type="text"
value={this.state.value}
onChange={this.handleSearch}/>
Table gets data from filteredData array
<ReactTable data={this.state.filteredData} columns={columns} />
working demo
来源:https://stackoverflow.com/questions/55815153/search-box-filtering-does-not-return-the-searched-result-react-react-table-fi