使用 socket.io 和 useEffect 导致延迟越多我添加到数组中?

Using socket.io and useEffect causing delays the more I add to an array?

下面的代码有效,但如果我越来越多地点击按钮,应用程序就会冻结,并且会在延迟后进行更新。每次按下按钮后,延迟都会显着增加。

如何避免这种情况 delay/freeze?

const ContactChatScreen = ({navigation}) => {
  const mySocket = useContext(SocketContext);
  const [chatMsgs, setChatMsgs] = useState([]);

  const sendMsg = () => {
    mySocket.emit('chat msg', 'test');
  };

  useEffect(() => {
    mySocket.on('chat msg', (msg) => {
      setChatMsgs([...chatMsgs, msg]);
    });
  });

  return (
    <View style={styles.container}>
      <StatusBar
        backgroundColor={Constants.SECONDN_BACKGROUNDCOLOR}
        barStyle="light-content"
      />
      {chatMsgs.length > 0
        ? chatMsgs.map((e, k) => <Text key={k}>{e}</Text>)
        : null}
      <Text style={styles.text}>Contact Chat Screen</Text>
      <MyButton title="test" onPress={() => sendMsg()} />
    </View>
  );

我可以通过更改以下内容来解决此问题:

useEffect(() => {
    mySocket.on('chat msg', (msg) => {
      setChatMsgs([...chatMsgs, msg]);
    });
    return () => {
      // before the component is destroyed
      // unbind all event handlers used in this component
      mySocket.off('chat msg');
    };
  }, [chatMsgs]);

添加 mySocket.off 是关键。