我在使用React Native的聊天应用程序中使用了Gifted Chat。当我发送短信或图像时,代码会执行,但是新消息不会出现在屏幕上,除非我滚动到聊天屏幕的顶部。如果我滚动到底部,则不会,如果我只滚动一半,仍会。仅当我滚动到屏幕顶部时,它才会更新。有人知道为什么会这样吗?这是我的代码。
import React, { useState } from 'react';
import { Image, StyleSheet, Text, View, Button, FlatList, TouchableOpacity, Alert } from 'react-native';
import { GiftedChat } from 'react-native-gifted-chat';
const Conversation = (props) => {
const chatId = props.chatId || "12345";
const userId = props.userId || "6789";
const [messages, setMessages] = useState([
{
_id: 1,
text: 'My message',
createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)),
user: {
_id: userId,
name: 'Jane',
avatar: 'https://randomuser.me/api/portraits/women/79.jpg',
}
},
{
_id: 3,
text: 'My next message',
createdAt: new Date(Date.UTC(2016, 5, 11, 17, 21, 0)),
user: {
_id: 4,
name: 'Gerry',
avatar: 'https://randomuser.me/api/portraits/women/4.jpg',
},
image: 'https://media1.giphy.com/media/3oEjHI8WJv4x6UPDB6/100w.gif',
}
]);
const d = Date.now();
const onSend = (msg) => {
console.log("msg : ", msg);
const message = {
_id: msg[0]._id,
text: msg[0].text,
createdAt: new Date(),
user: {
_id: userId,
avatar: "https://randomuser.me/api/portraits/women/79.jpg",
name: "Jane"
}
}
const arr = messages;
arr.unshift(message);
setMessages(arr);
}
return (
<GiftedChat
messages={messages}
onSend={newMessage => onSend(newMessage)}
user={{
_id: userId,
name: "Jane",
avatar: "https://randomuser.me/api/portraits/women/79.jpg"
}}
/>
)
}
export default Conversation;
答案 0 :(得分:0)
弄清楚了。 GiftedChat要求您使用一种名为append
的方法。
const onSend = (msg) => {
console.log("msg : ", msg);
// first, make sure message is an object within an array
const message = [{
_id: msg[0]._id,
text: msg[0].text,
createdAt: new Date(),
user: {
_id: userId,
avatar: "https://randomuser.me/api/portraits/women/79.jpg",
name: "Jane"
}
}]
// then, use the GiftedChat method .append to add it to state
setMessages(previousArr => GiftedChat.append(previousArr, message));
}