ReactJS通过多个值搜索输入

时间:2019-01-11 15:54:42

标签: javascript reactjs

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

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

我尝试使用其他一些问题,将json key value 组合到一个数组中,然后将其传递给搜索过滤器,但这没有用。 / p>

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 that I've created的链接。

  

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

2 个答案:

答案 0 :(得分:0)

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

here's a working code

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

答案 1 :(得分:0)

实际上,我在Fiddle中阅读了您的所有代码,但我向您提供了Fuse。在componentDidMount的代码中使用它并实现搜索。这非常方便。

const options = {
  shouldSort: true,
  threshold: 0.6,
  location: 0,
  distance: 100,
  maxPatternLength: 32,
  minMatchCharLength: 1,
  keys: [
    "title",
    "author.firstName"
  ]
};

const fuse = new Fuse(list, options); // "list" is the item array
const result = fuse.search(""); // put your string inside double quotation

result是您的答案。