简体   繁体   English

socket.io 客户端在本机反应中接收对同一事件的多个调用

[英]socket.io client receiving multiple calls to same event in react native

Whenver the user login into the application.每当用户登录到应用程序时。 he joins to its own userId in server via他通过

socket.join(uid)

whereas the nodejs endpoint looks like而 nodejs 端点看起来像

router.post("/secured/postmessage", (req,res)=>{
  const { message, receiverId } = req.body;

 io.to(receiverId).emit("newMessage", {
      msgBody: message,
      sender: req.currentUser,
    });
})

now the RN part:现在是 RN 部分:

Chat screen functional Component looks like聊天画面功能组件长这样

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(
  ...
  )

whereas the nodejs endpoint looks like而 nodejs 端点看起来像

router.post("/secured/postmessage", (req,res)=>{
 io.to(receiverId).emit("newMessage", {
      msgBody: messageResult,
      sender: req.currentUser,
    });
})

socket.on('newMessage') in Chat screen is getting fired multiple times, I dont know why聊天屏幕中的 socket.on('newMessage') 被多次触发,我不知道为什么

I think you can try adding socket event handler only when your Chat component mounted.我认为您只能在安装了 Chat 组件时尝试添加套接字事件处理程序。
In functional component, you can use React.useEffect().在功能组件中,您可以使用 React.useEffect()。

refer to below参考下面

React.useEffect(() => {
    socket.on("newMessage", ({ msgBody, sender }) => {
        setData((oldMessages) => [...oldMessages, msgBody]);
    });
},[]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM