搜索框过滤不return搜索结果- React redux-table+ filter

Search box filtering does not return the searched result- React+ react-table+ filter

我正在使用 react-table 作为数据网格。我正在实施基于 table 的搜索过滤。过滤似乎不起作用,因此返回空结果。我不知道哪里错了。

有人可以帮忙吗?

不胜感激

数据格式

let data =[  {id: 1, val1: "45GFSDSD", val2: "AKFHFDH83E3HHYE"},
             {id: 2, val1: "46FDGDGDGDG", val2: "AKFHFDH83E3HFGD"},
             {id: 3, val1: "56FDGGFGF", val2: "AERTFDH83E3HHYD"}
          ]

组件代码

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>            
      )
 }
}

您需要两个数组,一个用于 api 中的数据,一个用于过滤后的数据。你的状态会是这样的。

//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" }
  ]
};

当输入中的文本发生变化时,您需要一个过滤数据的函数

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))
   )
 });
};

您的输入

<input
  type="text"
  value={this.state.value}
  onChange={this.handleSearch}/>

Table 从 filteredData 数组中获取数据

<ReactTable data={this.state.filteredData} columns={columns} />

working demo