首页 > 解决方案 > 如何在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 是:这里是键盘方法这里是使用它的反应组件

标签: javascriptreactjsreact-hookssingletonuse-effect

解决方案


我猜你想要实现的目标可以通过使用 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]);

推荐阅读