React : Search Filter is not working Properly

2019-07-08 10:24发布

问题:

I am fetching records from server through API , API was built in Loopback . Actually On every page I am showing 5 records , currently It working fine I can navigate next or prev through pagination button and on every page it showing 5 records . Problem is that when User type something in search box , record are fetching correctly but when user remove query from search box it break the application flow . I mean to say that It showing all data not like 5 . I want that when user search something and remove text from search box it might not break application flow it must show 5 records after do query search . I will provide code please have a look and help me to figure out if I made some mistake . I am beginner to React and does not have much knowledge to fix this problem . Thanks Code

    class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Item: 5,
      skip: 0
    }

    this.handleClick = this.handleClick.bind(this);
  }

  urlParams() {
    return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
  }

  handleClick() {
    this.setState({skip: this.state.skip + 1})
  }

  render() {
    return (
      <div>
        <a href={this.urlParams()}>Example link</a>
        <pre>{this.urlParams()}</pre>
        <button onClick={this.handleClick}>Change link</button>
      </div>
    )
  }
}


ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))

回答1:

The problem is that when you empty the searchbox, keyword becomes "". You then check str.indexOf("") returns 0 which means your filter operation returns all items (like you are seeing)!!!

This returns everything when keyword is "":

 let filtered=this.state.allData.filter((item)=>{
      return item.companyName.indexOf(keyword) > -1
    });

To fix it - simply return [] if keyword is empty ("")

searchHandler(event){
    let keyword =event.target.value;
    let filtered=this.state.allData.filter((item)=>{
      return item.companyName.indexOf(keyword) > -1
    });
    if (keyword === "") {
      filtered = [];
    }
    this.setState({
      filtered
    })
  }


回答2:

I think, you need to change your searchHandler method and just clear filtered param when search keyword's length is 0.

searchHandler(event){
    const keyword = event.target.value
    const filtered = !keyword.length ? [] : this.state.allData.filter((item) => (item.companyName.indexOf(keyword) > -1))
    this.setState({ filtered })
}


回答3:

I think, It is because you are mutating state directly in searchHandler function. Can you try this?

searchHandler(event){
    let keyword =event.target.value;
    const data = [...this.state.allData];
    let filtered = data.filter((item)=>{
      return item.companyName.indexOf(keyword) > -1
    });
    this.setState({
      filtered
    })
  }