【问题标题】:filter conditions working individually but not together过滤条件单独工作但不能一起工作
【发布时间】:2022-01-15 18:03:38
【问题描述】:

请检查此 filterFunction 并告诉我如何改进它。这些过滤器单独工作,但不能一起工作

const filterFunction = (a) => {
  if (!includeKeyword && !searchVolume && !excludeKeyword && !longtailKeyword){
     return true
  } else if (includeKeyword && !searchVolume){
     return a.text.toLowerCase().includes(includeKeyword.toLocaleLowerCase())
  } else if (!includeKeyword && searchVolume){
     return  a.keyword_idea_metrics.avg_monthly_searches > parseInt(searchVolume)
  } else if (!searchVolume && excludeKeyword){
    return  !a.text.includes(excludeKeyword)
  } else if (!excludeKeyword && longtailKeyword){
    return  a.text.split(" ").length == longtailKeyword
  }  else {
    return  a.text.toLowerCase().includes(includeKeyword.toLocaleLowerCase()) && a.keyword_idea_metrics.avg_monthly_searches > parseInt(searchVolume)  && !a.text.includes(excludeKeyword) && a.text.split(" ").length <= longtailKeyword
  }
}

渲染函数

postRes.filter(filterFunction).map((data, index) => (

非常感谢您提前提供的帮助

【问题讨论】:

  • 什么不起作用?
  • 您需要在问题中提供更多信息:includeKeyword、searchVolume、excludeKeyword 和 longtailKeyword 是什么?您是否尝试基于这些布尔标志的 AND 或 OR 组合进行过滤?

标签: javascript reactjs filter react-hooks


【解决方案1】:

您当前正在传递一个带有参数的未调用函数,并将其作为filter 回调正确传递。

我想你可以试试postRes.filter((a) =&gt; filterFunction(a))...

【讨论】:

  • 您应该将未调用的函数传递给filter,否则它将立即执行:除非该函数是返回函数引用的工厂函数。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2018-07-26
  • 1970-01-01
  • 1970-01-01
  • 2020-01-20
  • 2021-08-05
相关资源
最近更新 更多