0

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

我怎样才能避免这种延迟/冻结?

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>
  );
4

1 回答 1

0

我可以通过改变这个来解决这个问题:

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是关键。

于 2021-07-25T21:13:41.807 回答