在ReactJS中使用.match()-匹配不是函数吗?

时间:2019-01-03 05:30:31

标签: reactjs filter match

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

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

但是我得到了:

TypeError: result.match is not a function

我在这里真的缺少明显的东西吗?漫长的一天:/

曲目 阵列的示例:

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件事,即原始数组,搜索项和过滤后的数组,但是过滤后的数组始终返回空。

enter image description here

2 个答案:

答案 0 :(得分:2)

似乎您的正则表达式已转换为字符串,并且正则表达式无法正常工作, 您可以这样做,当涉及到字符串插值时,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);

答案 1 :(得分:0)

在我的情况下,我正在尝试使用号码进行匹配。所以我在使用 {1, 7, 4, 9, 5} # initial List {1, 4, 5} is LNDS {1, 4, 9, 5, 7} # 7 inserted into {1, 4, 5} we have {1, 4, 5, 7} as LNDS {1, 4, 5, 7, 9} # 9 inserted into {1, 4, 5, 7} 之前就使用过.toString()