javascript - 如何在react中的useEffect挂钩中停止来自导入函数的新实例的先前调用
问题描述
我试图通过调用 useEffect Hook 中负责的函数来暂停/播放和更改下面代码中的乐器。playKeyboard 方法每次调用时都会使用一个新实例,但相反,我希望该状态完全停止并合并。
useEffect(() => {
if (keyboard.length > 0)
playKeyboard(keyboard, stat.pause, stat.index, stat.selectSound);
}, [keyboard, stat]);
const onInstrumentChange = (event) => {
const newStat = { ...stat, selectSound: { value: event.target.value } };
setStat(newStat);
};
负责创建声音的函数部分是:
async function playKeyboard(keyboardArray, pause, index, selectSound) {
var __audioSynth = new AudioSynth();
__audioSynth.setVolume(0.08);
var __octave = 4; //sets position of middle C, normally the 4th octave
//to select the instrument to play
// let selectSound = {
// value: "1"
// //"0" //piano
// // "1" //organ
// // "2" //acoustic
// // "3" //edm
// };
// Generates audio for pressed note and returns that to be played
var fnPlayNote = function(note, octave, duration) {
var src = __audioSynth.generate(selectSound.value, note, octave, duration);
var container = new Audio(src);
container.addEventListener("ended", function() {
container = null;
});
container.addEventListener("loadeddata", function(e) {
e.target.play();
});
有没有推荐的方法来停止以前注册或调用的函数。CodeSandbox 中的 FullCode 是:这里是键盘方法,这里是使用它的反应组件
解决方案
我猜你想要实现的目标可以通过使用 useEffect 和 Cleanup 来完成,在每个 useEffect 中,你都可以返回一个将在组件退出时调用的函数,
useEffect(() => {
if (keyboard.length > 0){
playKeyboard(keyboard, stat.pause, stat.index, stat.selectSound);
return stopKeyboard(arguments); // Implement the sound stop functionality here
}
}, [keyboard, stat]);
推荐阅读
- python - 更改 mayavi 动画中的点数
- sql - 寻找一种更高效的方式来检索 SQL 中组的前两行
- amazon-web-services - AWS Medical Comprehend 自定义
- javascript - 甜甜圈图 Vanilla JS 和 HTML Canvas
- arrays - 来自变量的数组像 Postman 中的字符串一样发送
- r - R - 不同回归模型的功率模拟
- json - How we can read a JSON file with Go Programming Language?
- python - Ubuntu 中的 Secret.Service 超时
- javascript - 每次按下按钮并显示结果时,我都会尝试将 JSON 对象推送到数组中
- symfony - "make:entity --regenerate" 创建了一个不正确的 (?) 函数