反应过滤状态而不破坏它

React filtering the state without ruining it

我正在尝试制作一个搜索功能,以呈现在搜索文本输入中匹配的人名。

问题是我将状态设置为与搜索匹配的项目,然后初始状态丢失,因此无法进行更多搜索,因为状态将为空。那么我如何"fill up"每次的状态呢?

或者可能有一些其他的方法没有实际设置我不知道的状态。

当在过滤器之前调用 handleSearch 函数时,我试图通过尝试重置到初始状态来修复此问题,但这不起作用。

import React from 'react';
import Header from './Header';
import peopleData from '../persons.json';

class App extends React.Component {
  constructor(){
    super();
    this.handleSearch = this.handleSearch.bind(this);
    this.state = {
      people: peopleData
    }
  }

  handleSearch(wordToMatch){
    this.setState({ people: peopleData }); //Attempt to reset to initial state
    const result = this.state.people.filter(d => {
      const regex = new RegExp(wordToMatch, 'gi');
      return d.Name.match(regex);
    });
    this.setState({ people: result })
  }

  render() {
    const list = this.state.people.map((d, i) => <li key={i}>{d.Name}</li>);
    return (
      <div className="myApp">
        <Header
          tagline={"testing"}
          handleSearch={this.handleSearch}
        />
        <ul className="contentBody">
          {list}
        </ul>
      </div>
    )
  }
}

export default App;

带有搜索输入的组件:

import React from 'react';

class Header extends React.Component {
  render() {
    return (
      <header>
        <input
          type="text"
          placeholder={this.props.tagline}
          ref={(input) => this.searchInput = input}
          onChange={() => this.props.handleSearch(this.searchInput.value)}
        >
        </input>
      </header>
    )
  }
}

export default Header;

我的数据是什么样的

[
  {
    "Name": "Adam",
    "Born": 1971
  },

  {
    "Name": "Bob",
    "Born": 1999
  },
etc etc for 20 more names

handleSearch 中设置 searchString 变量的状态。然后在 render 方法中,不是简单地映射状态,而是首先过滤人员列表,结果就是您映射的内容。

变化:

const list = this.state.people.map((d, i) => <li key={i}>{d.Name}</li>);

进入这个:

const list = this.state.people.filter(d => {
  const regex = new RegExp(this.state.searchString, 'gi');
  return d.Name.match(regex);
}).map((d, i) => <li key={i}>{d.Name}</li>);

这样state中的list就保持不变,渲染的时候过滤

setState 函数不会立即更新状态对象。因此,当您引用 this.state.people 时,它将引用 setState 调用之前的状态。您可以将代码更新为:

handleSearch(wordToMatch) {
    const result = peopleData.filter(d => {
        const regex = new RegExp(wordToMatch, 'gi');
        return d.Name.match(regex);
    });
    this.setState({
        people: result
    })
}