【问题标题】:What is the correct way to toggling a filter on a json array?在 json 数组上切换过滤器的正确方法是什么?
【发布时间】:2021-06-30 13:36:18
【问题描述】:

我有一个 json 对象数组,我希望能够显示所有对象,或者通过键值过滤它们来删除其中的一些对象。

我通过创建一个新常量来实现这一点:

const filtered = data.filter((item) => item.highVariance === false);

还有一个不同的常数:

const showHighVar = isHighVar ? data : filtered;

然后我有一个复选框,可以让我切换 shotHighVar 常量:

input type="checkbox" onChange={() => setHighVar(!isHighVar)}/>

为了稍后在代码中映射它:

{sorted(showHighVar).slice(0, 25 * pageIndex).map((x) => (...))}

但在我看来应该有更好的方法来做到这一点,但我想不通。

【问题讨论】:

    标签: html css reactjs jsx


    【解决方案1】:

    你的做法没有错。我要改变的一件事是,不是一直创建filtered 变量,而是在isHighVar 为假时过滤数据。所以你的代码应该是这样的 -

    const showHighVar = isHighVar ? data : data.filter((item) => item.highVariance === false);
    
    {sorted(showHighVar).slice(0, 25 * pageIndex).map((x) => ( .....))}
    

    或者当您在排序和切片后运行map 函数时。只需在 map 函数中添加 if 语句并检查 isHighVar 是否为 false 然后返回 null 否则做任何你正在做的事情。

    例如。

    {sorted(data).slice(0, 25 * pageIndex).map((x) => {
      if(isHighVar===false && x.highVariance!==false){
          return null; 
      }
    
      ....
    
    })}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多