javascript - 如何让消息以正确的顺序显示?
问题描述
我有一个问题,我的应用程序中的消息在页面刷新后没有以正确的顺序显示。最近的消息从下到上显示,而不是通常的从上到下(底部是最近的)。我怀疑它与添加要存储的消息的减速器功能有关。
调试器显示,当我发送一条新消息时,它显示在数组 [0] 的开头,而不是最后一个和最新的消息。我将如何解决这个问题?
减速机功能:
export const addMessageToStore = (state, payload) => {
const { message, sender } = payload;
if (sender !== null) {
const newConvo = {
id: message.conversationId,
otherUser: sender,
messages: [message],
};
newConvo.latestMessageText = message.text;
return [newConvo, ...state];
}
return state.map((convo) => {
if (convo.id === message.conversationId) {
debugger
const convoCopy = { ...convo };
convoCopy.messages.push(message);
convoCopy.latestMessageText = message.text;
debugger
return convoCopy;
} else {
return convo;
}
});
};
消息组件:
const Messages = (props) => {
const { messages, otherUser, userId } = props;
return (
<Box>
{messages.map((message) => {
const time = moment(message.createdAt).format("h:mm");
return message.senderId === userId ? (
<SenderBubble key={message.id} text={message.text} time={time} />
) : (
<OtherUserBubble key={message.id} text={message.text} time={time} otherUser={otherUser} />
);
})}
</Box>
);
};
聊天组件:
const ActiveChat = (props) => {
const classes = useStyles();
const { user } = props;
const conversation = props.conversation || {};
return (
<Box className={classes.root}>
{conversation.otherUser && (
<>
<Header
username={conversation.otherUser.username}
online={conversation.otherUser.online || false}
/>
<Box className={classes.chatContainer}>
<Messages
messages={conversation.messages}
otherUser={conversation.otherUser}
userId={user.id}
/>
<Input
otherUser={conversation.otherUser}
conversationId={conversation.id}
user={user}
/>
</Box>
</>
)}
</Box>
);
};
const mapStateToProps = (state) => {
return {
user: state.user,
conversation:
state.conversations &&
state.conversations.find(
(conversation) => conversation.otherUser.username === state.activeConversation
)
};
};
解决方案
尝试修改reducer函数如下:
export const addMessageToStore = (state, payload) => {
const {message,sender} = payload;
if (sender !== null) {
return [{
id: message.conversationId,
otherUser: sender,
messages: [message],
latestMessageText: message.text
},
...state
];
}
return state.map((convo) => {
if (convo.id === message.conversationId) {
const convoCopy = {
...convo,
latestMessageText: message.text
};
convoCopy.messages.unshift(message);
return convoCopy;
} else {
return convo;
}
});
};
推荐阅读
- spring - Spring中的@order和@DependsOn注解有什么区别?
- python - 熊猫,根据另一列的信息计算日期列中发生的更改次数?
- javascript - 反应不始终如一地返回“名称”属性
- nativescript - nativescript app_resources 包含 app_resources nidificate
- mongodb - MongoDB性能下降
- php - 如何使用firebase auth通过电话号码重置密码
- python - Python - 检查子类覆盖是否与父类不同
- react-admin - react-admin 是否为演示站点中的客户提供登录
- reactjs - observable.takeUntil... 和 observable.pipe(takeUntil
- node.js - 从ppt文件节点js中提取笔记