首页 > 解决方案 > 通知被阅读后通知徽章不会消失?

问题描述

这是我在导航栏中的通知图标标记,这不会在阅读通知后删除带有未读通知计数的徽章:

const notificationsIcon =
     notifications && notifications.length && notifications.filter(n => !n.read).length ?
         <Badge badgeContent={notifications.filter(n => !n.read).length}>
             <NotificationsIcon /> //Material-UI Icon
         </Badge> : <NotificationsIcon />

但这有效:

let notificationsIcon;
        if (notifications && notifications.length > 0) {
            notifications.filter(n => n.read === false).length > 0
                ? (notificationsIcon = (
                    <Badge
                        badgeContent={
                            notifications.filter(n => n.read === false).length
                        }
                    >
                        <NotificationsIcon />
                    </Badge>
                ))
                : (notificationsIcon = <NotificationsIcon />);
        } else {
            notificationsIcon = <NotificationsIcon />;
        }

我真的不明白为什么第二个标记有效而第一个无效,

const mapStateToProps = state => ({
  notifications: state.user.notifications
})

notificationsIcon变量将包含在带有 Material-UI 元素的 render 方法IconButton中,单击该元素时会向 redux 存储发送一个操作以将通知read属性更改为 true,这将更新组件中的通知。

标签: javascriptreactjsreduxjsx

解决方案


我试过这个只是为了测试你的第一个逻辑,这个有效:

let notifications = [{read: true}, {read: true}]
const notificationsIcon =
     notifications && notifications.length && notifications.filter(n => !n.read).length ?
         "yes" : "no";
         console.log(notificationsIcon);

无法尝试使用实际代码,您可以提供 stackblitz 或 plunker。也试试这个:

const notificationsIcon =
 notifications && notifications.length && notifications.filter(n => !n.read).length ?
     (<Badge badgeContent={notifications.filter(n => !n.read).length}>
         <NotificationsIcon /> //Material-UI Icon
     </Badge>) : (<NotificationsIcon />);

推荐阅读