在不破坏状态的情况下对状态进行反应

时间:2017-06-22 20:02:47

标签: reactjs react-jsx

我试图制作一个搜索功能,用于呈现搜索文本输入中匹配的人的姓名。

问题是我将状态设置为与搜索匹配的项目,然后初始状态丢失,因此不再进行搜索,因为状态将为空。那么我如何填补"国家每次?

或许还有其他方法没有实际设置我不知道的状态。

我尝试在过滤器之前调用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

2 个答案:

答案 0 :(得分:2)

<md-radio-group class="md-primary" ng-model="plan"> <div flex ng-repeat="planInfo in plans" class="plan-options"> <md-radio-button ng-value="planInfo._id" name="plan" class="md-primary" ng-checked="hasPlanID == planInfo._id" required> <h2 class="plan-name">{{planInfo.name}}</h2> <h3 class="plan-price">${{planInfo.price}}</h3> </md-radio-button> </div> </md-radio-group> 中设置handleSearch变量的状态。然后在render方法中,不是简单地映射状态,而是首先过滤人员列表,结果就是你映射的结果。

变化:

searchString

进入这个:

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

这样,状态中的列表保持不变,并在渲染时进行过滤。

答案 1 :(得分:2)

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