如何解决React Native如何过滤具有3个以上参数的Flatlist?
您好,各位程序员,我是React Native的新手,真的很陌生,因此在继续之前,我将快速总结示例和代码。
我正在从api获取产品列表,并将其存储在两个数组中:products[]
和catalogue[]
目录数组用于存储从api接收的所有项目。产品列表是Flatlist将用来显示数据的数组。当应用过滤器时,产品中的项目应被过滤,以便Flatlist也可以更新屏幕上新过滤的数据。
现在这是我从api获取的所有对象数据中的一个简化的对象。
Object {
"designNumber": "CHE-S-207 RW","id": 292187,"imageUrl": "http://company.shop.org/images/shop/136/4.jpg","itemCategory": "BRACELET","itemStatus": "INSTOCK","itemType": "CHE","quantity": "1","rfidTag": "Item4","shopId": 136,"skuNumber": "Item4",}
我将根据对象数据用于过滤器的主要值为itemStatus
,itemCategory
和itemType
。
我在状态对象中使用这些变量将值存储在其中,这些值将使用多选选择器从“筛选器屏幕” UI中进行选择。
state = {
products: [],catalogue: [],itemStatus: "",//Binary values. Only one string value for this one
itemCategory: [],//Multiple values in array
itemType: [],//Multiple values in array
};
现在我们来谈谈主要交易。假设我已经使用过滤器屏幕UI为这些过滤器参数选择了某些值。例如,itemStatus: "AVAILABLE"
,itemCategory: ["MENS","WOMENS","CORPORATE"]
和itemType: ["COMMON","UNCOMMON","SALE","EXCLUSIVE"]
因此,用通俗易懂的术语来说,我使用的UI选择了“状态可用”,“类别3”和“类型4”。现在最后有一个应用过滤器按钮。我在这里调用filterProducts()
之类的函数,该函数将采用这些多个参数并相应地过滤我的Flatlist项目。
请记住,catalogue[]
数组具有从api中提取的全部数据,而products[]
数组就是在Flatlist中显示的内容。因此,理想情况下,无论来自过滤器功能的任何新过滤数据都应更新products[]
数组,以便我认为也将在Flatlist上进行更新。
我的问题?我在堆栈和介质上阅读的每篇文章始终只使用Searchbar搜索过滤器示例。基本上只接受1个过滤器字符串,然后过滤列表。
但是,如果像我想要实现的示例中那样有多个参数要过滤怎么办?如果您有3个参数,并且每个参数可以有多个值(4个或更多)在过滤时要考虑该怎么办?如何应用如此复杂的过滤级别,然后将过滤后的项目返回到我的Flatlist?
<Button title="Apply Filter" onPress={() => this.filterProducts}/>
filterProducts = () => {
//Logic to take all the filter parameters and their selected values
this.state.products = if({/** No filters are applied */}){
return this.state.catalogue //Return original data
} else {
this.state.catalogue.filter({/** Apply complex filter logic here}).map(){
//return filtered items list
}
}
}
也许逻辑流程是这样的?除非我不知道如何一次过滤具有这么多过滤参数的列表。任何帮助将不胜感激。谢谢。
更新1:根据u / TommyLeong的建议,我更新了代码。这是我的过滤器功能和逻辑的样子:
state = {
isFilterActive: false,products: [],itemCategory: [],itemType: [],}
//Get data from the api
fetchProducts = aysnc () => {
//Make the api call and get the response
const data = await response.json();
this.setState({
products: data.data,//Originally show all the data from the api
catalogue: data.data,//Store all the data from the api
});
};
//Filter Function
filterProducts = () => {
console.log("function called",this.state.isFilterActive);
//Pack all filter data in one query object
let query = {
itemStatus: this.state.itemStatus,itemCategory: this.state.itemCategory,itemType: this.state.itemType,};
console.log("Filter object",Object.entries(query));
if (this.state.isFilterActive) {
const filteredData = this.state.catalogue.filter(function (item) {
return Object.entries(query).every(([key,value]) =>
value.includes(item[key])
);
});
console.log("Result: Filtered Array",filteredData);
this.setState({ products: filteredData });
} else {
//Return original data is isFilterActive == false
this.setState({ products: this.state.catalogue });
}
};
render(){
return(
//Contains my views. My Filter screen has a bunch of pickers
//and a apply filter button
<DropDownPicker
label="Item Status"
multipleSelection={true} //More than one values can be selected
items={/*define my filter values for itemStatus here*/}
onChangeItem={(item) => {
this.setState({ itemStatus: item.value});
}
/>
<DropDownPicker
label="Item Category"
items={/*define my filter values for itemCategory here*/}
onChangeItem={(item) => {
//item here is an array of selected values
this.setState({ itemCategory: item});
}
/>
<DropDownPicker
label="Item Type"
multipleSelection={true} //More than one values can be selected
items={/*define my filter values for itemType here*/}
onChangeItem={(item) => {
//item here is an array of selected values
this.setState({ itemType: item });
}
/>
<Button
title="Apply Filter"
onPress={() => {
this.setState({ isFilterActive: true },() =>
this.filterProducts()
);
}}
)
}
现在我的代码和逻辑已经很清楚了,让我们继续讨论新问题。 过滤器功能中的过滤器逻辑100%有效! 但是仅当所有3个过滤器属性均选择了某个值时
//my filter object in the function
let query = {
itemStatus: this.state.itemStatus,};
情况1: console.log,当所有3个过滤器类别均选择了一些值时:
Filter object Array [
Array [
"itemStatus","INSTOCK",],Array [
"itemCategory",Array [
"MENS",Array [
"itemType",Array [
"COMMON","SALE"
],]
Result: Filtered Array Array[
Object: {
//first item matching all 3 filter criteria
},Object: {
//2nd item matching all 3 filter criteria
},Object: {
//3rd item matching all 3 filter criteria
},]
情况2: console.log,如果未为3个过滤条件之一选择任何值。对于这种情况,我选择itemType,即itemType []为空白。
Filter object Array [
Array [
"itemStatus",Array [],//Array is blank here because no filter
//values were picked for itemType
],]
Result: Filtered Array Array [] //No items returned to me,Flatlist becomes empty
我当然知道问题出在此过滤器逻辑中,但是我无法直截了当地,为什么当三个条件之一中存在未定义的值时,过滤器不起作用。最重要的是,再次idk如何修复它:(
//Current filter Logic
if (this.state.isFilterActive) {
const filteredData = this.state.catalogue.filter(function (item) {
return Object.entries(query).every(([key,filteredData);
this.setState({ products: filteredData });
} else {
//Return original data is isFilterActive == false
this.setState({ products: this.state.catalogue });
}
解决方法
这就是我要解决的方法。
- 创建一个变量调用
hasFilterApply
,以存储有关用户是否应用了任何过滤器的布尔值。从用户界面删除所有过滤器时,需要将布尔值设置回FALSE。 - 每次过滤之前,我都会根据
hasFilterArray
决定要进行过滤的数组(目录/产品)。如果为true,则表示我应该继续使用this.state.products
,因为它包含最新的过滤产品列表。 - 渲染时,再次检查
hasFilterApply
是否为TRUE。如果是,则渲染this.state.products
,否则仅渲染this.state.catalgoues
this.state = {
hasFilterApply: false,// update hasFilterApply to TRUE when one or more filter is applied,set to FALSE when no filter is applied
catalogues: [],// keep original response
products: [] // this will be the final render product list
}
/*
* Assuming this is how your catalgoues will be
const catalogues = [{"designNumber":"CHE-S-207 A","id":1,"imageUrl":"http://company.shop.org/images/shop/136/4.jpg","itemCategory":"BRACELET","itemStatus":"AVAILABLE","itemType":"EXCLUSIVE","quantity":"1","rfidTag":"Item1","shopId":1,"skuNumber":"Item1",},{"designNumber":"CHE-S-207 B","id":2,"itemCategory":"MENS","itemStatus":"NO","itemType":"SALE","rfidTag":"Item2","shopId":2,"skuNumber":"Item2",{"designNumber":"CHE-S-207 C","id":3,"itemCategory":"WOMENS","itemType":"UNCOMMON","rfidTag":"Item3","shopId":3,"skuNumber":"Item3",{"designNumber":"CHE-S-207 D","id":4,"itemCategory":"CORPORATE","itemType":"COMMON","rfidTag":"Item4","shopId":4,"skuNumber":"Item4",{"designNumber":"CHE-S-207 E","id":5,"rfidTag":"Item5","shopId":5,"skuNumber":"Item5",]
*/
getFromAPI = async () => {
const catalogues = await getCatalogues();
this.setState({ catalogues })
}
filterStatus = (filterValue) => {
const latestList = hasFilterApply ? this.state.products : this.state.catalogues;
const newList = []
latestList.filter((product)=>{
if(product.itemStatus === filterValue){
newList.push(product)
}
}
this.setState({ products: newList })
}
filterCategory = (filterValue) => {
const latestList = hasFilterApply ? this.state.products : this.state.catalogues;
const newList = []
latestList.filter((product)=>{
if(product.itemCategory === filterValue){
newList.push(product)
}
}
this.setState({ products: newList })
}
filterType = (filterValue) => {
const latestList = hasFilterApply ? this.state.products : this.state.catalogues;
const newList = []
latestList.filter((product)=>{
if(product.itemType === filterValue){
newList.push(product)
}
}
this.setState({ products: newList })
}
renderMyProducts = () => {
// At the end before you decide render the products,you should know which ARRAY (catalgoues/products) should be passed to your component.
// Do checking on whehter "hasFilterApply" is TRUE or false. If false,then pass catalgoues,otherwise pass products to your component.
}
render(){
return(
// render your components
)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。