[英]Sort Users in chat by most recent messages with React
我需要通過他們發送的新消息和更新消息對我的 ReactJS 聊天應用程序中的用戶數組進行排序,並在每條新消息(例如 WhatsApp 或電報)處進行更新。
下面是兩個不同的arrays的簡化界面:用戶和消息:
我正在使用 momentjs 處理日期,存儲的日期格式是這樣的時間戳:2021-03-26 00:17:50
interface userProps {
id: string;
chat_id: string;
first_name: string;
last_name: string;
}
interface messagesProps {
id?: string;
chat_id?: string;
content?: string;
send_by?: string;
visualized?: boolean;
created_at?: string;
}
所有的消息都存儲在數組中並由 chatID 過濾,這兩個 arrays 有共同點。
有誰知道這個挑戰的最佳解決方案是什么?
我不太確定您的聊天室是如何參與其中的,但您可以使用如下簡單的 JS 代碼讓用戶按 id 排序:
const sortedUserIds = messages // you array of messagesProps
.sort() // you already know the correct way to sort your messages
.map(m => m.send_by)
.filter(m => m.send_by !== null)
const sortedUsers = [...new Set(sortedUserIds)].map(id => users.find(u => u.id === id))
既然你已經參與了反應,你可以基於帶有反應鈎子的messages
數組觸發上面的代碼:
const [users, setUsers] = useState([]);
useEffect(() => {
run the code above to get sorted users
setUsers(your sorted users);
}, [messages])
return (
<ul>
{users.map(u => <li>{u.first_name}</li>)}
</ul>
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.