React Native中如何筛选已读/未读应用内通知并调整显示顺序
解决通知筛选与排序问题
首先得处理通知数据的筛选和排序,再修正下拉切换的逻辑,就能实现未读通知显示在已读通知下方的需求。
1. 筛选并排序通知数据
假设你已经从API拿到了完整的通知列表notifications,按下面的方式处理:
// 把已读和未读通知分开筛选 const readNotifications = notifications.filter(notify => notify.isRead); const unreadNotifications = notifications.filter(notify => !notify.isRead); // 合并时让已读在前,未读在后 const sortedNotifications = [...readNotifications, ...unreadNotifications];
要是需要按时间排序(比如最新的通知排在前面),可以给两组数据分别排序再合并:
// 按创建时间降序排序(假设每条通知有createdAt字段) const sortByLatest = (a, b) => new Date(b.createdAt) - new Date(a.createdAt); const sortedRead = readNotifications.sort(sortByLatest); const sortedUnread = unreadNotifications.sort(sortByLatest); const sortedNotifications = [...sortedRead, ...sortedUnread];
2. 修复下拉切换的逻辑问题
你当前的handleDropDownToggle代码有语法错误(多行逻辑没加大括号),而且标记已读的逻辑也不对。调整后的代码:
const { mutate: markRead } = useMutation(markNotificationRead, { onSuccess: () => { // 标记成功后,要重新获取通知数据或者更新本地状态,确保排序生效 // 比如调用获取通知列表的refetch方法,或者直接更新本地的notifications数组 }, onError: () => { // 这里可以加错误提示,比如弹窗告知用户标记失败 }, }); const handleDropDownToggle = () => { const newOpenStatus = !isDropDownOpen; setIsDropDownOpen(newOpenStatus); toggleDropdown(item._id); // 只有打开面板的时候才标记该通知为已读 if (newOpenStatus) { markRead(item?._id); } };
3. 分组渲染已读和未读通知
在UI里分别渲染两组通知,就能清晰区分已读和未读:
<div className="notification-panel"> <h3>已读通知</h3> {sortedRead.map(notify => ( <div key={notify._id} className="read-notification-item"> {/* 这里写通知的具体内容,比如标题、时间等 */} </div> ))} <h3>未读通知</h3> {sortedUnread.map(notify => ( <div key={notify._id} className="unread-notification-item"> {/* 未读通知的内容 */} </div> ))} </div>
这样调整后,打开通知面板时未读通知就会显示在已读通知的下方,而且标记已读的操作也能正确同步到数据里,保证排序始终生效。
内容的提问来源于stack exchange,提问作者Rahil Raja
相关产品推荐
相关产品推荐

