首页 > 解决方案 > ReactJS: Filter rendering of a list by whole names only?

问题描述

I am currently rendering a list of data returned from an API using the map() function as follows:

renderLocation() {
    return this.props.locations.map(location => {
      return (
        <div key={location.id}>
          <div className="location">
            <h1>
              {location.name}
              {location.airport_code}
            </h1>
            <div className="location-secondary-info">
              <span>
                <i className="material-icons">airplanemode_active</i>
                {location.description}
              </span>
            </div>
          </div>
        </div>
      );
    });
  }

I now want to filter the rendering, so that the only locations that are rendered are those that have a correct name field value. My API data looks like this:

enter image description here

I only want locations to be rendered if the locations.name is an actual valid city name.

So for instance, a location with a name of "Chicago O'Hare" would be a valid city name, and should be displayed. A location with a name of "Chicago O'Hare A5C" however, should not be rendered seeing it has the A5C at the end which makes it invalid.

标签: arraysreactjsecmascript-6filter

解决方案


一种方法可能是使用正则表达式根据位置name字段上是否存在字母数字子字符串后缀来过滤位置,方法如下:

const filteredLocations = this.props.locations.filter(location => {
    return !location.name.match(/[A-Z0-9]+$/)
});

上面的逻辑基本上是说:

“过滤位置名称末尾没有字母数字单词的所有位置”

renderLocation()可以通过以下方式将其集成到您的功能中:

renderLocation() {

    /* Filter locations with name that doesn't have alphanumeric suffix word   */
    const filteredLocations = this.props.locations.filter(location => {
        return !location.name.match(/[A-Z0-9]+$/)
    });

    /* Render only the filtered location with name Chicago O'Hare */ 
    return filteredLocations.map(location => {
      return (
        <div key={location.id}>
          <div className="location">
            <h1>
              {location.name}
              {location.airport_code}
            </h1>
            <div className="location-secondary-info">
              <span>
                <i className="material-icons">airplanemode_active</i>
                {location.description}
              </span>
            </div>
          </div>
        </div>
      );
   });
}

希望有帮助


推荐阅读