简体   繁体   English

JavaScript 调用函数 4 次,但我只需要执行一次函数

[英]JavaScript calling function 4 times but I need to execute function only one time

I have listener when any change in volume execute callback function 4 times callback call other function I need that function execute only one what is the best way当音量发生任何变化时我有监听器执行回调函数4次回调调用其他函数我需要该函数只执行一个什么是最好的方法

when lisiner detect any change callback call recognitionCameraBySoundVolum() 4 time当lisiner检测到任何变化回调调用recognitionCameraBySoundVolum() 4次

volumeListener = SystemSetting.addVolumeListener((data) => { 
    recognitionCameraBySoundVolum();
});

need to excute this function only once instead of 4只需执行此功能一次而不是 4

   const recognisionCameraBySoundVolum = () => {
        console.log("hi from recognitionCameraBySoundVolum "); 
    }

Did you use the useEffect hook?您是否使用了 useEffect 挂钩?

It should look something like this.它应该看起来像这样。

useEffect(() => {
    volumeListener = SystemSetting.addVolumeListener((data) => { 
        recognitionCameraBySoundVolum();
    });

    // return remove listener method in the cleanup section 
}, []);

this worked with me这对我有用

useEffect(() => {
const volumeListener = SystemSetting.addVolumeListener( (data) => { 
    const volume = data.value;  

}); 
return () => 
SystemSetting.removeVolumeListener(volumeListener)  
}, [])

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

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