gpt4 book ai didi

javascript - 在 React 上过滤 json

转载 作者:行者123 更新时间:2023-12-03 01:33:44 25 4
gpt4 key购买 nike

我必须通过两种方式过滤这个数组,一种是用户键入时,另一种是当他单击某个类别时,我的代码如下:

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 都保留在那里,但只有最后一个可以工作

如何同时制作两件作品?

最佳答案

您可以链接过滤器:

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

关于javascript - 在 React 上过滤 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51172882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com