我刚刚在我的react native和nodejs项目中完成了套接字的设置,但当消息发送时,我的平面列表仍然没有立即更新,我需要刷新应用程序才能更新。
我以为通过使用套接字,这将工作,但它仍然是不工作的。每当我的用户打开聊天,我得到例如。用户:1已加入控制台中的会话1,这表明套接字正在工作。
客户端
function ChatScreen({route,navigation}) {
const message = route.params.message;
const [messages, setMessages] = useState(message.Messages);
const [text, setText] = useState('');
const [socket, setSocket] = useState(null);
const { user } = useAuth();
const index = route.params.index;
const updateView = route.params.updateView;
useEffect(() => {
const newsocket =io.connect(socketURL)
setMessages(messages);
newsocket.on('connect', msg => {
console.log(`user: ${user.id} has joined conversation ${message.id}`)
setMessages(messages=>messages.concat(msg))
setSocket(newsocket)
});
return()=>newsocket.close;
}, []);
const onSend = (ConversationId,senderId,receiverId,message) => {
messagesApi.sendMessage({ConversationId,senderId,receiverId,message});
setText("")
const to = (user.id===route.params.message.user1?
route.params.message.user2:route.params.message.user1)
socket.emit('message', { to: to, from: user.id, message, ConversationId });
};
const updateText=(text)=>{
setText(text);
}
return (
<FlatList
inverted
data={message.Messages}
keyExtractor={(message) => message.id.toString()}
renderItem={({item,index})=>(
<>
<Text>
{moment(item.createdAt).fromNow()}
</Text>
<MessageBubble
text={item.message}
mine={item.senderId !== user.id}
/>
</>
)}
/>
<View style={styles.messageBoxContainer}>
<TextInput
onChangeText={updateText}
value={text}
/>
<TouchableOpacity
onPress={()=>{onSend(message.id,user.id,(user.id===message.user1?
message.user2:message.user1),text)}}>
</TouchableOpacity>
</View>
);
}
服务器端
const express = require("express");
const app = express();
const http = require("http");
const socket = require("socket.io")
const server=http.createServer(app);
const io =socket(server)
io.on('connection', (socket) => {
console.log("connected")
socket.on('message', (data) => {
console.log(data)
socket.join(data.ConversationId);
io.sockets.in(data.to).emit('send_message', { message:
data.message, to: data.to });
});
});
* 更新 *
客户端
const message = route.params.message;
const [messages, setMessages] = useState([]);
const [text, setText] = useState('');
const [socket, setSocket] = useState(null);
const { user } = useAuth();
useEffect(() => {
const newsocket =io.connect("http://192.168.1.103:9000")
newsocket.on('connect', msg => {
console.log(`user: ${user.id} has joined conversation
${message.id}`)
setSocket(newsocket)
setMessages(message.Messages)
});
newsocket.on("send_message", (msg) => {
console.log("this is the chat message:", msg);
setMessages([ { ...message.Messages },...messages]);
});
return()=>newsocket.close;
}, []);
const onSend = (ConversationId,senderId,receiverId,message) => {
console.log("sent")
messagesApi.sendMessage({ConversationId,senderId,receiverId,message});
setText("")
const to = (user.id===route.params.message.user1?
route.params.message.user2:route.params.message.user1)
socket.emit(
'message', { to: to, from: user.id, message,ConversationId });
};
const updateText=(text)=>{
setText(text);
}
<FlatList
inverted
data={messages}
keyExtractor={(message) => message.id.toString()}
renderItem={({item,index})=>(
<>
<Text>
{moment(item.createdAt).fromNow()}
</Text>
<MessageBubble
text={item.message}
mine={item.senderId !== user.id}
/>
</>
)}
bounces={false}
/>
<View style={styles.messageBoxContainer}>
<TextInput
onChangeText={updateText}
value={text}
/>
<TouchableOpacity
onPress={()=>{
onSend(
message.id,
user.id,
(user.id===message.user1?message.user2:message.user1),
text
)}}
>
<Text>Send</Text>
</TouchableOpacity>
</View>
服务器端
io.on('connection', (socket) => {
console.log("connected")
socket.on('message', (data) => {
console.log(data)
socket.emit('send_message', { message: data.message, receiverId:
data.to,senderId:data.from,conversationId:data.ConversationId })
});
});
使用更新的代码,当我打开聊天我得到
user: 43 has joined conversation 4 ---- on client side console
connected ---- on server side console
使用更新的代码,当我发送消息时,我得到
this is the chat message: Object {
"conversationId": 25,
"message": "You",
"receiverId": 47,
"senderId": 43,
} --- in my client side console
{ to: 47, from: 43, message: 'You', ConversationId: 25 } ---- server
side console
但是我得到一个错误
undefined is not an object (evaluating 'message.id.toString')
我想我的问题是我没有正确地发出消息id,因此我的平面列表不知道它。要获得消息id,我需要先将消息存储在db中
* 最新更新 *
客户端
const message = route.params.message;
const [messages, setMessages] = useState([]);
const [text, setText] = useState('');
const [socket, setSocket] = useState(null);
const { user } = useAuth();
useEffect(() => {
const newsocket =io.connect(socketURL)
newsocket.on('connect', msg => {
console.log(`user: ${user.id} has joined conversation
${message.id}`)
setSocket(newsocket)
setMessages(message.Messages)
});
newsocket.on("send_message", (msg) => {
console.log("this is the chat message:", msg);
const data = [...messages];
console.log(data)
data.push(msg);
setMessages(data);
});
return(()=>newsocket.close());
}, []);
const onSend = (ConversationId,senderId,receiverId,message) => {
console.log("sent")
messagesApi.sendMessage({ConversationId,senderId,receiverId,message});
setText("")
const to = (user.id===route.params.message.user1?
route.params.message.user2:route.params.message.user1)
socket.emit(
'message', { to: to, from: user.id, message,ConversationId });
};
const updateText=(text)=>{
setText(text);
}
<FlatList
inverted
data={messages}
keyExtractor={(item,index)=>index.toString()}
renderItem={({item,index})=>(
<>
<Text>
{moment(item.createdAt).fromNow()}
</Text>
<MessageBubble
text={item.message}
mine={item.senderId !== user.id}
/>
</>
)}
bounces={false}
/>
<View style={styles.messageBoxContainer}>
<TextInput
onChangeText={updateText}
value={text}
/>
<TouchableOpacity
onPress={()=>{
onSend(
message.id,
user.id,
(user.id===message.user1?message.user2:message.user1),
text
)}}
>
<Text>Send</Text>
</TouchableOpacity>
</View>
服务器端
io.on('connection', (socket) => {
console.log("connected")
socket.on('message', (data) => {
console.log(data)
socket.emit('send_message', { message: data.message, receiverId:
data.to,senderId:data.from,conversationId:data.ConversationId })
});
});
现在使用新的更新代码,当我发送消息时,只有新消息被呈现给发送者,而没有以前的消息,接收者在聊天时没有收到任何东西。
3条答案
按热度按时间kxkpmulp1#
因此,从你们的回答中,我得到的印象是,为了让它发挥作用,你们需要大致做到以下几点:
1.在您的客户端,您必须有一个套接字监听更新:
socket.on('send_message', (e) => doSomethingWith(e));
1.一旦你让你的套接字监听更新,你就可以处理接收到的信息。确保你的组件重新呈现并显示正确信息的最简单的方法是使用状态。所以一旦从套接字接收到消息,你就可以设置消息
setMessages(socketMessage)
1.然后将
messages
状态传递给Flatlist中的data
。我还将它传递到Flatlist中的extraData
字段also。如果您有redux,您可能希望将消息保存在那里,那么就不需要在组件中设置本地状态,您可以直接从props中获取它。希望这对您有所帮助,如果您有任何其他问题,请随时提出。
编辑1:
我只需要从上面提到的解决方案中复制代码:
您通过套接字接收消息,然后必须对其进行处理。不使用redux?将其设置为本地状态或顶级上下文,无论哪种都适用于您的应用。
编辑2:
socket.on('connect', ...)
是socket理解的一个标准事件。它不是你的消息,你需要把它分开。cig3rfwq2#
试试这边
vyu0f0g13#
这会起作用的!