【问题标题】:Using .match() in ReactJS - match is not a function?在 ReactJS 中使用 .match() - match 不是一个函数?
【发布时间】:2019-01-03 05:30:30
【问题描述】:

我正在尝试使用 match() 过滤 React 中数组的结果:

if (this.props.search) {
   tracks.filter(result => {
      return result.match(`/${this.props.search}/gi`);
   });
}

但我得到了:

TypeError: result.match is not a function

我在这里遗漏了一些非常明显的东西吗?这是漫长的一天:/

tracks 数组示例:

0:
  active: 1
  artist: "CJ Bolland"
  date_added: "2019-01-03 05:08:10"
  date_modified: "2019-01-03 05:09:01"
  duration: "00:05:54"
  filename: "1546488490.mp3"
  id: 2
  in_playlist: false
  online: 1
  seconds: 354
  time_ago: "1 hour ago"
  title: "Sugar Is Sweeter (AVH Mix)"
  type: "track"
  user_id: 4

1:
  active: 1
  artist: "Cristoph"
  date_added: "2019-01-03 05:08:46"
  date_modified: "2019-01-03 05:10:01"
  duration: "00:06:34"
  filename: "1546488526.mp3"
  id: 3
  in_playlist: false
  online: 1
  seconds: 394
  time_ago: "1 hour ago"
  title: "Guffaz"
  type: "track"
  user_id: 3

**** 编辑 **** 这是实施Just code 的解决方案后发生的情况的屏幕截图(在 SO 上运行良好,但在 React 中不行)。如您所见,我记录了 3 件事,原始数组、搜索词和过滤后的数组,但过滤后的数组总是返回空。

【问题讨论】:

  • 什么是轨道,里面有什么数据?
  • 这是一个关联数组
  • 可以分享tracks的样本数据吗?
  • 刚刚添加 ;)
  • 你正在使用match 函数到你的过滤函数中的一个对象

标签: reactjs filter match


【解决方案1】:

似乎您的正则表达式已转换为字符串并且正则表达式无法正常工作, 你可以这样做,当涉及到字符串插值时,regexp 对象总是很方便。

return result.match(new RegExp(`${search}`,'gi'));

var tracks = [{
  artist: "CJ Bolland",
  title: "Sugar Is Sweeter (AVH Mix)"
}, {
  artist: "Cristoph",
  title: "Guffaz"
}];
var search = "sug";
var filtered = tracks.filter(result => {
  return result.artist.match(new RegExp(`${search}`, 'gi')) || result.title.match(new RegExp(`${search}`, 'gi'));
});
console.log(filtered);

【讨论】:

  • 我可以将此匹配同时应用于艺术家和标题字段吗?
  • @spice 是的,请检查我的编辑,您可以使用 && 或 ||根据您的要求
  • 谢谢兄弟。它仍然无法正常工作。我正在为我搜索的任何内容返回一个空数组。可能是由于轨道数组和搜索字符串都是从父级传递下来的道具吗?我不认为 .filter 变异了?
  • 是的,我知道这并没有真正的帮助。哦,无论如何感谢您的帮助。我会弄清楚。现在我知道我错误地使用了 match,这让我更接近了一步,所以再次感谢您指出这一点。
  • 噢!找到了......我使用的是AND 运算符而不是OR。这就是为什么我没有得到任何结果。它现在正在工作,如果有迹象表明我需要睡觉……哈哈。再次感谢兄弟;)
【解决方案2】:

就我而言,我试图在数字中使用匹配。所以我在使用.match()之前只使用了.toString()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 2019-02-23
    • 2019-09-27
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多