在useEffect
中,notifications
从数据库中获取:
useEffect(() => {
if (props.loading != true) {
props.fetchNotifications(currentUserId, submissionId)
}
}, [])
在return语句的某处,我有以下代码在通知列表上应用过滤器,并检查剩余列表的长度是否大于零。然后,如果是这样,我将使用相同的filter语句来计算这次显示的计数。但是,我做了两次计算,创建了冗余代码。我想知道在React中是否有解决问题的方法。
props.notifications &&
<div className="col-sm-4">
<div className="mb-3">
<h5 className="text-primary bg-light pl-1 pt-2 pb-2">
<i className="fa fa-bell-o"></i> Notifications
<span className="badge badge-pill badge-primary small ml-2">
{
Object.keys(props.notifications)
.filter(function (id) {
return props.notifications[id].isDiscussionType == false &&
props.notifications[id].isRead == false
}).length > 0 &&
<span>{
Object.keys(props.notifications)
.filter(function (id) {
return props.notifications[id].isDiscussionType == false &&
props.notifications[id].isRead == false
}).length} new
</span>
}
</span>
</h5>
<NotificationList isDiscussionType={false} />
</div>
答案 0 :(得分:1)
您可以将结果存储在一个常数中,仅执行一次filter
操作:
const notificationsLength = props.notifications ? Object.keys(props.notifications).filter(function (id) {
return props.notifications[id].isDiscussionType == false &&
props.notifications[id].isRead == false
}).length : 0
return (
<span className="badge badge-pill badge-primary small ml-2">
{
notificationsLength &&
<span>{notificationsLength} new</span>
}
</span>
)
答案 1 :(得分:1)
您可以从收益中提取出来并创建一个变量,例如:
const filteredNotifications = Object.keys(props.notifications)
.filter(id => props.notifications[id].isDiscussionType == false
&& props.notifications[id].isRead == false })
然后您可以做类似的事情
<span className="badge badge-pill badge-primary small ml-2">
{
filteredNotifications.length > 0 &&
(<span>{filteredNotifications.length} new </span>)
}
</span>