如何在Firebase中获取每条消息发送者的邮箱ID并显示
实现Firebase聊天消息旁显示用户邮箱ID
步骤1:发送消息时将用户邮箱存入Firestore
在SendMessage组件中,需要从当前认证用户中获取邮箱,并在添加消息文档时将邮箱字段一并存入:
修改后的SendMessage代码:
function SendMessage({ scroll }) { const [msg, setMsg] = useState('') async function sendMessage(e) { e.preventDefault() // 从auth.currentUser中获取正确的email属性 const { uid, photoURL, email } = auth.currentUser await db.collection('messages').add({ text: msg, photoURL, uid, // 将邮箱存入为emailid字段(对应Chat组件中读取的字段名) emailid: email, createdAt: firebase.firestore.FieldValue.serverTimestamp() }) setMsg('') scroll.current.scrollIntoView({ behavior: 'smooth' }) } return ( <div> <form onSubmit={sendMessage}> <div className="input1"></div> <input style={{maxWidth: "1000px",color:"white", background: "rgb(59, 59, 59)", width: "800px", fontSize: '15px', fontWeight: '550', marginLeft: '25px', marginBottom: '-3px' }} placeholder='Message...' type="text" value={msg} onChange={e => setMsg(e.target.value)} /> <button style={{ width: '20%', fontSize: '15px', fontWeight: '550', margin: '4px 5% -13px 5%', maxWidth: '200px', color:"white"}} type="submit" >Send</button> </form> </div> ) }
步骤2:在Chat组件中显示邮箱
你的Chat组件已经预留了{emailid}的显示位置,现在可以添加空值优化,避免用户邮箱未获取到时显示空白:
修改后的Chat组件消息渲染部分:
{messages.map(({ id, text, photoURL, uid , emailid}) => ( <div key={id}> <div className={`msg ${uid === auth.currentUser.uid ? 'sent' : 'received'}`}> <img style={{ width: "40px", height: "40px",margin: "2px 5px",borderRadius:"50%"}} src={photoURL} alt="用户头像" /> {/* 添加空值判断,显示友好提示 */} <span style={{marginRight: "10px"}}>{emailid || '未知邮箱'}</span> <p>{text}</p> </div> </div> ))}
额外提示
- 确保用户已完成Firebase Auth登录,可在
Chat组件开头添加登录状态校验:if (!auth.currentUser) { return <div>请先登录</div> } - 若你希望将存储的字段名改为
email,只需在SendMessage的add方法中写email: email,同时在Chat组件的map解构中把emailid替换为email即可。
内容的提问来源于stack exchange,提问作者Vinay
相关产品推荐
相关产品推荐

