arrays - 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:
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.
解决方案
一种方法可能是使用正则表达式根据位置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>
);
});
}
希望有帮助
推荐阅读
- javascript - 如何在javascript中选择div?
- sql - 从 SCN_TO_TIMESTAMP(ORA_ROWSCN) 中提取日期
- c# - 转换 XML
我有将 Json 作为输入参数的 Webservice SOAP 方法。
//For sample string jsonString = "[{"Year":"2020","UserId":"1","Comp":"20","DeptId":"32","CategoryId":"53","ItemId":"0"}]"; string[] processStrin
- git - 使用 ssh 查看我的 GitHub 组织中的存储库
- mysql - 使用 Node.js 并在 AWS lambda 中编写的关闭数据库连接(Mysql)的正确方法是什么
- c++ - C++ ADO Excel 记录删除
- google-apps-script - 如何使此函数在具有多个工作表 ID 的循环中运行?
- json - ansible 将 json 解析为 include_tasks 循环
- amazon-ec2 - 从 Azure Devops 部署到 VPN 后面的 AWS 机器
- android - Flutter - 如何在侦听器延迟后检查值?