简体   繁体   English

socket.io 使用效果清理 function 反应

[英]socket.io useEffect cleanup function react

I am calling socket.on function inside component but I want to stop it when the component unmount, I'm using a functional component.我在组件内部调用 socket.on function 但我想在组件卸载时停止它,我正在使用功能组件。

useEffect(() => {
    socket.on("new-chat-message", (firstname, lastname, content, date) => {
      dispatch(
        addMessage({
          firstname: firstname,
          lastname: lastname,
          content: content,
          date: date,
        })
      );
    });
  }, [dispatch, socket]);

I need to know how to set the cleanup function for this useEffect.我需要知道如何为此 useEffect 设置清理 function。

As explained in the doc here正如这里的文档中所解释的

useEffect(() => {
    const callback = (firstname, lastname, content, date) => {
      dispatch(
        addMessage({
          firstname: firstname,
          lastname: lastname,
          content: content,
          date: date,
        })
      );
    }

    socket.on("new-chat-message", callback);

    return () => {
       socket.off("new-chat-message", callback);
    }
}, [dispatch, socket]);

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

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