首页 > 解决方案 > ReactJS 通过多个值搜索输入

问题描述

我在我的页面上有一个搜索选择过滤器。我遇到的问题是我似乎无法使用多个 json 值进行搜索。

示例值是{ "id": "1", "role": "teacher", "subject": "mathematics", "name": "Jonathan Kovinski" },我希望能够使用键和值。

我尝试使用其他一些关于将 json组合到单个数组并将其传递给搜索过滤器的问题,但它没有用。

text = data.filter(info => {
  return Object.keys(info).map(function(key) {
    var singleOne = JSON.stringify(info[key]);
    console.log(info, "This is the json one")
  }).toLowerCase().match(searchString);
});

这是使用所有代码创建的 JS Fiddle 的链接。

我正在尝试将我的搜索栏设置为使用所有键和值来搜索和排序数据。

标签: javascriptreactjs

解决方案


我建议您将filtered数据放在 state 中的单独键中,以防您想恢复到原始结果,使用Obeject.values代替并在函数中Object.keys过滤,datahandleChange

这是一个工作代码

class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      data: [],
      searchString: "",
      filtered: []
    };
    this.handleChange = this.handleChange.bind(this);
  }

  componentDidMount() {
    this.fetchData();
  }

  handleChange(e) {
    var value = e.target.value;
    this.setState({
      searchString: value,
      filtered: this.state.data.filter(e =>
        Object.values(e)
          .join(" ")
          .toLowerCase()
          .match(value)
      )
    });
  }

  fetchData() {
    fetch("https://api.myjson.com/bins/lo3ls")
      .then(response => response.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          data: json,
          filtered: json
        });
      })
      .catch(error => console.log("parsing failed", error));
  }

  render() {
    var { isLoaded, data } = this.state;
    const searchString = this.state.searchString.trim().toLowerCase();
    let text = this.state.data;
    console.log(text);
    if (searchString.length > 0) {
      text = text.filter(info => {
        return info.role.toLowerCase().match(searchString);
      });
    }
    return (
      <div>
        <input
          type="text"
          id="searchbar"
          value={this.state.searchString}
          onChange={this.handleChange}
          placeholder="Search"
          name="device"
        />

        <select className="category-select" name="categories" onChange={this.handleChange}>
          {data.map(info => (
            <option value={info.role}>{info.role}</option>
          ))}
        </select>
        {/* map through the filtered ones*/}
        {this.state.filtered.map(info => (
          <div className="display">
            <span className="role">Role: {info.role}</span>
            <span> Name: {info.name}</span>
            <span>, Subject: {info.subject}</span>
          </div>
        ))}
      </div>
    );
  }
}

ReactDOM.render(<Hello name="World" />, document.getElementById("container"));

推荐阅读