React Native如何过滤具有3个以上参数的Flatlist?

如何解决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",}

我将根据对象数据用于过滤器的主要值为itemStatusitemCategoryitemType

我在状态对象中使用这些变量将值存储在其中,这些值将使用多选选择器从“筛选器屏幕” 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 });
  }

解决方法

这就是我要解决的方法。

  1. 创建一个变量调用hasFilterApply,以存储有关用户是否应用了任何过滤器的布尔值。从用户界面删除所有过滤器时,需要将布尔值设置回FALSE。
  2. 每次过滤之前,我都会根据hasFilterArray决定要进行过滤的数组(目录/产品)。如果为true,则表示我应该继续使用this.state.products,因为它包含最新的过滤产品列表。
  3. 渲染时,再次检查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 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res