socket.io 客户端在 React Native 中接收到对同一事件的多次调用

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

每当用户登录到应用程序时。他通过

在服务器中加入了自己的 userId
socket.join(uid)

而 nodejs 端点看起来像

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

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

现在是 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(
  ...
  )

而 nodejs 端点看起来像

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

socket.on('newMessage') 在聊天屏幕中被触发多次,我不知道为什么

我认为您可以尝试仅在安装聊天组件时添加套接字事件处理程序。
在功能组件中,您可以使用 React.useEffect()。

参考下文

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