fix(ChatWindow): 增加对消息对象的空值检查以防止运行时错误

- 在hasVideoStateChange函数中优先检查消息对象和内容是否存在
- 在groupMessagesByTime函数中过滤掉null和undefined的消息
- 在renderMessage函数中添加null检查并为缺失id的消息生成临时key
This commit is contained in:
超级老白兔
2025-09-04 14:51:23 +08:00
parent 923f0e99b9
commit 54464efdcd

View File

@@ -44,13 +44,13 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
const prevMessages = prevMessagesRef.current; const prevMessages = prevMessagesRef.current;
const hasVideoStateChange = currentMessages.some((msg, index) => { const hasVideoStateChange = currentMessages.some((msg, index) => {
// 首先检查消息对象本身是否为null或undefined
if (!msg || !msg.content) return false;
const prevMsg = prevMessages[index]; const prevMsg = prevMessages[index];
if (!prevMsg || prevMsg.id !== msg.id) return false; if (!prevMsg || !prevMsg.content || prevMsg.id !== msg.id) return false;
try { try {
// 检查msg.content和prevMsg.content是否为null或undefined
if (!msg.content || !prevMsg.content) return false;
const currentContent = const currentContent =
typeof msg.content === "string" typeof msg.content === "string"
? JSON.parse(msg.content) ? JSON.parse(msg.content)
@@ -533,17 +533,22 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
// 用于分组消息并添加时间戳的辅助函数 // 用于分组消息并添加时间戳的辅助函数
const groupMessagesByTime = (messages: ChatRecord[]) => { const groupMessagesByTime = (messages: ChatRecord[]) => {
return messages.map(msg => ({ return messages
time: formatWechatTime(msg?.wechatTime), .filter(msg => msg !== null && msg !== undefined) // 过滤掉null和undefined的消息
messages: [msg], .map(msg => ({
})); time: formatWechatTime(msg?.wechatTime),
messages: [msg],
}));
}; };
const renderMessage = (msg: ChatRecord) => { const renderMessage = (msg: ChatRecord) => {
// 添加null检查防止访问null对象的属性
if (!msg) return null;
const isOwn = msg?.isSend; const isOwn = msg?.isSend;
return ( return (
<div <div
key={msg.id} key={msg.id || `msg-${Date.now()}`}
className={`${styles.messageItem} ${ className={`${styles.messageItem} ${
isOwn ? styles.ownMessage : styles.otherMessage isOwn ? styles.ownMessage : styles.otherMessage
}`} }`}
@@ -561,7 +566,7 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
{!isOwn && ( {!isOwn && (
<div className={styles.messageSender}>{msg?.senderName}</div> <div className={styles.messageSender}>{msg?.senderName}</div>
)} )}
{parseMessageContent(msg.content, msg)} {parseMessageContent(msg?.content, msg)}
</div> </div>
</div> </div>
</div> </div>