下面的代码工作,但如果我点击按钮越来越多,应用程序冻结和更新发生延迟后。每次按下按钮后,延迟时间显著增加。
我怎样才能避免这种延迟/冻结?
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
是关键。