我正在重构我的代码,使之更加干净和可重用。但是,在我重构代码后,functions/features 之一不起作用

I'm refactoring my code more clean and reusable. However after I refactored the code, one of the functions/features doesn't work

嘿,伙计们,我正在重构我的代码,使其更加简洁并且可重用。这是我想做的。
我希望你们能理解我在做什么

然而,在我重构代码后,'stop playing music' 功能不起作用。当我在 window 上进行点击事件时,它应该可以工作。你们能帮我解决一下吗?谢谢


重构前

const LoginPhone = () => {
    const domNavigate = useDomNavigate();
    const {openKioskAlert} = useContext(KioskAlertContext);
    const [phoneNumber, setPhoneNumber] = useState([]);
    const [isPlaying, setIsPlaying] = useState(true);
    const audioFile = new Audio(`/sounds/hello.mp3`);

    // play audio sound
    const playSound = () => {
        audioFile.play();
    };

    // stop audio sound
    const stopSound = () => {
        audioFile.pause();
        audioFile.currentTime = 0;
    };


    useEffect(() => {
        playSound();
// when there's click event on window, it stops playing the music
        const clickHandler = () => stopSound();
        window.addEventListener('click', clickHandler);
        return () => window.removeEventListener('click', clickHandler);
    }, []);


重构后

loginPhone.tsx
import {voiceAudio} from '../../src/common/utils/voice';

const LoginPhone = () => {
    const domNavigate = useDomNavigate();
    const {openKioskAlert} = useContext(KioskAlertContext);
    const [phoneNumber, setPhoneNumber] = useState([]);
    const {playAudio, stopAudio} = voiceAudio('login-phone');

    useEffect(() => {
        playAudio();
        return () => stopAudio();
    }, []);
工具 > voice.ts

export const voiceAudio = (title: string) => {
    const audioFile = new Audio(`/sounds/${title}.mp3`);
    const playAudio = () => audioFile.play();
    const stopAudio = () => {
        audioFile.pause();
        audioFile.currentTime = 0;
    };
    return {
        playAudio,
        stopAudio,
    };
};



它不起作用,因为您在分配新音频后丢失了对旧音频的引用。 先暂停,再分配新的声音