如何根据时间显示发送和接收消息



如果发送方发送消息,消息会显示在ui的右侧,接收方从ui的左侧获得,但当发送方向接收方发送另一条消息时,消息应该显示在下端,但会显示在顶端

我想作为显示消息

received message
send message
received message
send message

但我收到了类似的信息

received message
received message
received message
received message
send message
send message
send message
send message

这是代码:

const time = new Date();
const formattedTime = time.toLocaleString("en-US", { hour: "numeric", minute: "numeric", seconds: "numeric });
<div className="nano-content pad-all" tabIndex={0} style={{right: '-17px'}}>
<ul className="list-unstyled media-block">
<li className="mar-btm" id="media-left">
{
receiveMessages.map((receivemessage,key) => {
return <div>
<div className="media-left">
<img src="https://bootdey.com/img/Content/avatar/avatar1.png" className="img-circle img-sm" alt="Profile Picture" />
</div>
<div className="media-body pad-hor">
<div className="speech">
<p value={key} className="mar-btm">{receivemessage}</p> 
<span class="time_date">{formattedTime}</span>
</div>
</div>
</div>
})
}
</li>
<li className="mar-btm" id="media-right">             
{
messages.map((message,key) => {
return <div>
<div className="media-right">
<img src="https://bootdey.com/img/Content/avatar/avatar2.png" className="img-circle img-sm" alt="Profile Picture" />
</div>
<div className="media-body pad-hor speech-right mt-2">
<div className="speech">  
<p value={key} className="mar-btm">{message}</p>  
<span class="time_date">{formattedTime}</span>
</div>
</div>
</div>
})
}       
</li>
</ul>
</div>

请提前帮我谢谢。

您只是将一个数组映射到另一个数组,因此消息应该显示为原样。您需要的不是一个消息字符串数组,而是一个更复杂的对象,其中包含一些元数据:(1(消息发送的日期。(2( 是谁发送的,当然还有(3(消息本身。类似:

messsageObj = {
// always good to add an unique id to use as the `key` property when using .map
id: 1, 
message: 'My message',
createDate: '25/12/2020 22:00:00',
createUser: 1
}

例如:

// in `mergeMessagesArray` you add all messages to a single list, 
// ordering by the date they were sent
const mergedMessages = mergeMessagesArray(sentMessages, receivedMessages)
return (
<div>
{mergedMessages.map(m => (
// use unique id as key to avoid weird bugs
<div key={m.id}
// when mapping the messages array just check the user who created the 
// message against your current logged in user and render accordingly
className={m.createUser === currentUser ? 'show-on-right' : 'show-on-left'}>
{m.message}
</div>
)}
</div>
)

相关内容

最新更新