我的 Firebase 结构是: -2 收藏:聊天和用户 -聊天集合有:聊天中的用户(数组)(一对一),它还有其他名为“消息”的集合 在 SSR 中,我试图在选择聊天后获取聊天和消息。 功能是:
export async function getServiceSideProps(context) {
const ref = db.collection("chats").doc(context.query.id);
// PREPARE MESSAGES
const messagesRes = await ref
.collection("messages")
.orderBy("timestamp","asc")
.get();
const messages = messagesRes.docs.map((doc) => ({
id:doc.id,
...doc.data(),
}))
.map((messages) => ({
...messages,
timestamp:messages.timestamp.toDate().getTime(),
}));
//PREPARE THE CHAT
const chatRes = await ref.get();
const chat = {
id:chatRes.id,
...chatRes.data(),
};
return {
props:{
messages:JSON.stringify(messages),
chat:chat,
},
};
} 聊天组件是:
function Chat({chat,messages}) {
console.log(chat);
const [user] = useAuthState(auth);
const recipientUserEmail = chat.users.filter((userFilter) => userFilter !== user.email)[0];
return <div className="container">
<Head>
<title>Chat with: {recipientUserEmail}</title>
</Head>
<div className="chat">
<div className="chat__header">
<div className="chat__header__left">
<Avatar className="avatar" />
<div className="header__chatInfo">
<h2>test@gmail.com</h2>
<p>Last active: 2minutes ago</p>
</div>
</div>
<div className="chat__header__right">
<IconButton>
<AttachFileIcon />
</IconButton>
<IconButton>
<MoreVertIcon />
</IconButton>
</div>
</div>
</div>
<SideBar />
</div>
}
在recipientUserEmail 的函数中,当我尝试进入users 数组时,它说TypeError:无法读取未定义的属性'users'。 有什么帮助吗?