在useEffect
中,notifications
从数据库中获取:
useEffect(() => {
if (props.loading != true) {
props.fetchNotifications(currentUserId, submissionId)
}
}, [])
返回语句中的某个地方有以下代码在通知列表上应用过滤器,并检查其余列表的长度是否大于零。然后,如果是的话,我使用相同的过滤器语句来计算这次显示的计数。但是,我正在两次进行计算,创建冗余代码。我想知道是否有解决方案,这是问题。
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>
您可以将结果存储在常数中,只能执行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>
)
您可以从返回中提取并创建一个变量,例如:
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>