unk*_*guy 3 node.js socket.io reactjs socket.io-1.0 react-native
每当用户登录应用程序时。他通过以下方式加入到服务器中自己的 userId
socket.join(uid)
Run Code Online (Sandbox Code Playgroud)
而nodejs端点看起来像
router.post("/secured/postmessage", (req,res)=>{
const { message, receiverId } = req.body;
io.to(receiverId).emit("newMessage", {
msgBody: message,
sender: req.currentUser,
});
})
Run Code Online (Sandbox Code Playgroud)
现在是 RN 部分:
聊天屏幕功能组件看起来像
export default function Chat({ navigation }) {
//receiveing the socket as props from previous screen
const { contact, socket } = navigation.state.params;
// console.log("in conversation contact is ", contact);
const [data, setData] = useState([
{
id: 8,
date: "9:50 am",
type: "in",
message: "Lorem ipsum dolor sit a met",
},
]);
//this gets fired multiple times <--------
socket.on("newMessage", ({ msgBody, sender }) => {
setData((oldMessages) => [...oldMessages, msgBody]);
});
//handleSubmit gets fired when user types message and press SEND
const handleSubmit(){
//sending the post request to server with message
axios.post(baseUrl + "/secured/postmessage", {
message: message,
receiverId: contact._id,
})
}
return(
...
)
Run Code Online (Sandbox Code Playgroud)
而nodejs端点看起来像
router.post("/secured/postmessage", (req,res)=>{
io.to(receiverId).emit("newMessage", {
msgBody: messageResult,
sender: req.currentUser,
});
})
Run Code Online (Sandbox Code Playgroud)
聊天屏幕中的 socket.on('newMessage') 被多次触发,我不知道为什么
小智 5
我认为您可以尝试仅在安装聊天组件时添加套接字事件处理程序。
在功能组件中,您可以使用React.useEffect()。
参考下文
React.useEffect(() => {
socket.on("newMessage", ({ msgBody, sender }) => {
setData((oldMessages) => [...oldMessages, msgBody]);
});
},[]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3441 次 |
| 最近记录: |