【发布时间】:2018-12-15 06:49:25
【问题描述】:
我在我的 react-native 应用程序中使用 react-native-gifted-chat。正如我在this 图像中所示,多次显示相同的消息,message: Yes getting new msg 的位置也与其实际位置不同。
我的问题与this 相同。谁能帮我解决这个问题。
提前谢谢你。
【问题讨论】:
标签: reactjs react-native react-native-gifted-chat
我在我的 react-native 应用程序中使用 react-native-gifted-chat。正如我在this 图像中所示,多次显示相同的消息,message: Yes getting new msg 的位置也与其实际位置不同。
我的问题与this 相同。谁能帮我解决这个问题。
提前谢谢你。
【问题讨论】:
标签: reactjs react-native react-native-gifted-chat
我的问题得到了解决。 @Ron你是对的,但在我的情况下,问题是不同的。我通过更改参数格式解决了这个问题。它采用不同的格式,我通过的方式也不同,所以它们相互冲突。这是可能对其他人有用的解决方案。
parse = snapshot => {
const { timestamp: numberStamp, text } = snapshot.val();
const { key: _id } = snapshot;
const createdAt = moment(snapshot.val().createdAt, "DD/MM/YYYY hh:mm:ss");
const user = { };
var temp_data = snapshot.val()
if(snapshot.val().name == this.state.temp_logged_name) {
user._id = 1;
user.name = temp_data.name;
user.avatar = temp_data.avatar;
}
const message = {
_id,
createdAt,
text,
user,
};
return message;
};
【讨论】:
我也遇到过这个问题。我在我的移动应用程序上设置了react-native-gifted-chat。在另一端,我设置了一个简单的 HTML 页面,其中包含一个脚本来初始化 Websocket 连接并在 onsend 事件上发送消息。后来我意识到,虽然唯一 id 是在应用程序端生成的(因为 id 是由库本身生成的),但另一端不存在这种类型的东西。
基本上,当消息缺少唯一 id _id 时,就会出现这种奇怪的行为。在执行GiftedChat.append(previousMessages, messages) 时,每条消息必须至少具有以下属性。
{
_id: 1,
text: 'Hello developer',
createdAt: new Date(),
user: {
_id: 2
}
}
【讨论】:
这背后可能有两个原因,
1) 每条消息都应该传递一个唯一的 id,所以只需使用 uuidv4 npm 包并将其附加到对象的 _id 属性。
例子:
messages: GiftedChat.append(previousState.messages, {
_id: uuidv4(), // or use Math.round(Math.random() * 1000000)
text: text,
createdAt: new Date(),
user: {
_id: 2,
name: "React Native",
avatar: "https://placeimg.com/140/140/any"
},
image: attachment
})
2) 第二种可能性可能是在您用来启动用户之间聊天的网关上。因此,一些网关已经知道多次重复消息的问题。您可以在每次收到新消息并推送到聊天屏幕时进行字符串比较,但不建议这样做。
【讨论】:
我通过简单地将过滤器应用于 useLayout Effect 中的传入消息来解决这个问题:
useLayoutEffect(() => {
db.collection('Chats').doc(docID).collection('messages').orderBy("createdAt", "desc").onSnapshot(snapshot => {
setMessages(
prev =>
prev
.filter((ftr,index,self) => ftr?.user?._id !== loginUser?.id) //login user id is the current user's id you can do the same for recieved messages
.concat
(snapshot.docs.map(doc => doc.data({
_id: doc?.id,
user: doc.data().user,
text: doc.data().text,
createdAt:new Date(doc.data().createdAt),
})
))
)
})
},[])
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
【讨论】: