在React上过滤json

时间:2018-07-04 11:44:06

标签: javascript json reactjs getjson

我必须用两种方法过滤此数组,一种是在用户键入内容时,另一种是当他单击某个类别时,我的代码是这样的:

https://gist.github.com/pedroapfilho/dbd48b1bf10c4ff625929cb2f67c6b41

import React, { Component } from "react";
import "./App.css";
import appslist from "../apps.json";

import Sidebar from "../components/Sidebar/Sidebar";
import HeaderSearch from "../components/HeaderSearch/HeaderSearch";
import ListContainer from "../components/ListContainer/ListContainer";
import Pagination from "../components/Pagination/Pagination";

class App extends Component {
  state = {
    list: appslist,
    searchfield: "",
    selectedcategory: "",
    currentpage: 1,
    itensperpage: 3
  };

  onSearchChange = event => {
    this.setState({ searchfield: event.target.value });
  };

  onClickCategory = event => {
    this.setState({ selectedcategory: event.target.id });
  };

  render() {
    const {
      list,
      searchfield,
      currentpage,
      itensperpage,
      selectedcategory
    } = this.state;

    let filteredList;

    filteredList = list.filter(list => {
      return list.name.toLowerCase().includes(searchfield.toLowerCase());
    });

    filteredList = list.filter(list => {
      return list.categories[0].toLowerCase().includes(selectedcategory.toLowerCase());
    });

    return (
      <div className="flex-container">
        <Sidebar categorylist={list} selectedCategory={this.onClickCategory} />
        <section className="apps-list">
          <HeaderSearch searchChange={this.onSearchChange} />
          <ListContainer list={filteredList} />
          <Pagination currentPage={currentpage} itensperpage={itensperpage} />
        </section>
      </div>
    );
  }
}

export default App;

我把两个filteredList都留在那里,但是只有最后一个可以工作

我如何同时使两个作品正常?

1 个答案:

答案 0 :(得分:1)

您可以链接过滤器:

filteredList = list
    .filter(list => list.name.toLowerCase().includes(searchfield.toLowerCase()))
    .filter(list => list.categories[0].toLowerCase().includes(selectedcategory.toLowerCase()));

或者甚至将其写为单个过滤器:

filteredList = list.filter(
    list => list.name.toLowerCase().includes(searchfield.toLowerCase()) &&
            list.categories[0].toLowerCase().includes(selectedcategory.toLowerCase())
);

如果您需要OR行为而不是AND,请使用单一过滤器方法,显然将&&替换为||

关于评论中的问题:

要使用过滤器中的所有类别,可以使用someevery(取决于所需的逻辑):

filteredList = list.filter(
    list => list.name.toLowerCase().includes(searchfield.toLowerCase()) &&
            list.categories.some(
                cat => cat.toLowerCase() === selectedcategory.toLowerCase()
            )
);