[英]How to fix Error: Objects are not valid as a React child (found: [object Promise])
Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
in ul (at ChatRoom.js:16)
It throws this error for some reason.由于某种原因,它会引发此错误。 Here's my code:这是我的代码:
const [messages] = useCollectionData(query, { idField: 'id' });
return (
<div className={classes.ChatRoomContainer}>
<ul>
{messages ? messages && messages.map(async msg => {
const messageClass = msg.userId === props.userId ? classes.Sent : classes.Recieved;
let username;
await firebase.firestore().collection('users').doc(msg.author).get().then(doc => {
username = doc.data().userName;
});
return <li className={messageClass + ' ' + classes.Message} key={msg.id}>
<label>{msg.author !== props.userId ? username : 'You'}</label>
<p className={classes.MessageContent}>{msg.messageContent}</p>
</li>
}) : <p>Loading...</p>}
</ul>
<form className={classes.Form} onSubmit={(e) => props.onMessageSentHandler(e)}>
<input className={classes.Input} placeholder="Type your message..." onChange={(e) => props.onInputChangedHandler(e)} value={props.messageInput} />
<button className={classes.Btn}><FontAwesomeIcon color="white" icon='paper-plane' className={classes.PaperPlaneIcon} /></button>
</form>
</div>
)
Is there some way to fix it?有什么办法可以解决吗? It only appears if I use async by the way.仅当我顺便使用 async 时才会出现。
You're trying to execute the Promise twice.您正在尝试执行 Promise 两次。
async/await
and .then().catch
are two different syntaxes. async/await
和.then().catch
是两种不同的语法。
Try this:尝试这个:
let doc = await firebase.firestore().collection('users').doc(msg.author).get();
and then read the username from it:然后从中读取用户名:
return (
<li className={messageClass + ' ' + classes.Message} key={msg.id}>
<label>{msg.author !== props.userId ? doc.data().username : 'You'}</label>
<p className={classes.MessageContent}>{msg.messageContent}</p>
</li>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.