首页 > 解决方案 > 将过滤器应用于 React 数组并显示过滤后的结果

问题描述

我正在尝试过滤用 React Js 编写的数组,但到目前为止,我一直没有成功收到未定义的错误。我想过滤一些值低于 10 的图像。

我尝试应用过滤器的方式看起来像: {this.images.filter((image:any={}) => image.value < 10)} 但有些不对劲。

我的过滤器有什么问题以及如何编写它以获得有效的代码?

export class somePageImages{

  images: any[] = [
    { img: 'http://www.someimage.com/', value: 4, title: 'Image 1', description: 'A description 1' },
    { img: 'http://www.someimage.com/', value: 6, title: 'Image 2', description: 'A description 2' },
    { img: 'http://www.someimage.com/', value: 10, title: 'Image 3', description: 'A description 3' },
  ]

  render() {
    return (
      <Host>
        <ol>
          { this.images.map((image:any={}) =>
            <li>
            <img src={image.img}></img>
            <h1>{image.title}</h1>
            <p>{image.description}</p>
          </li>
          )}
        {this.images.filter((image:any={}) => image.value < 10)}
        </ol>

      </Host>
    );
  }

}

标签: javascriptarraysreactjstypescript

解决方案


I had to put the filter in a different position to work properly:

this.images.filter((image:any={}) => image.value < 50).map((image:any={})

This way it's working properly without any undefined error


推荐阅读