javascript - 在 React 中停止路由更改的音频?

标签 javascript reactjs frontend react-router

大家。我还在习惯 React 和 React Router,这是我没有弄清楚的一件事。

所以,我有一个应用可以同时播放视频(静音)和音轨。我正在使用 React Player两个都玩。我的 View 看起来像这样(VideoPlayer 是 react-player 标签):

<div>
    <VideoPlayer url={this.props.audio} playing={this.state.playing} />
    <VideoPlayer url={this.props.video} playing={this.state.playing} />
</div>

这个设置对我很有效,我可以通过一个共同的状态来播放和控制它们。我可以通过连接到按钮的事件处理程序停止它们:

handleStop() {
    this.setState({playing: false})
}

这也行。

然而,问题是一旦我导航到不同的路线,音频(可能还有视频)仍然在后台播放。实际上,让我换个说法,当我改变路线时,音频在后台重新启动

看完this page from the react-router docs ,我曾尝试在各种生命周期事件中包含调用 handleStop 的逻辑,但没有一个能达到目的。到目前为止,我已经尝试在 componentWillReceivePropscomponentWillUpdatecomponentDidUpdatecomponentWillUnmount< 中调用 handleStop/.

我得到的最接近的是在 componentWillUnmount 中调用,但我总是收到有关设置未安装组件状态的错误(这也没有意义,如果它被调用 卸载之前?)。

那么,有没有人知道在哪里调用 handleStop?

提前致谢。

最佳答案

我知道这个问题已有 4 年多了,但我今天遇到了这个问题,想分享我的解决方法...

import React, { useRef, useEffect } from 'react';
import waves from '../audio/waves.mp3';
    
const RockyCoast = (props) => {
    // the audio variable needs to be stored in a ref in order to access it across renders
    let audio = useRef();
    // start the audio (using the .current property of the ref we just created) when the component mounts using the useEffect hook
    useEffect(() => {
        audio.current = new Audio(waves)
        audio.current.play()
    }, [])
    // Stop the audio when the component unmounts
    // (not exactly what you asked re React Router, but similar idea)
    useEffect(() => {
        return () => {
            audio.current.pause()
            console.log("in cleanup")
        }
    }, [])
    ...

    return (
        <>
            ...
        </>
    )
}
export default RockyCoast;

它正常工作的一些关键原因是因为我们将 audio 变量声明为 React ref,以便我们可以再次访问它以暂停它卸载。同样重要的是,两个 useEffect 调用的依赖数组是相同的(在我的例子中它们是空的,以便它们像 componentDidMountcomponentWillUnmount )。

问题是专门询问有关使用 React Router 更改路由的问题,因此您的特定情况可能需要做更多的工作,但如果像我一样,您有一个父组件正在为我们需要此功能的路由呈现,例如这个:

<Route exact path="/habitat/rocky_coast">
    <RockyCoast />
</Route>

(音频在页面上播放,然后在我们导航到另一个页面时停止),这个解决方案效果很好。

希望这能帮助其他一些像我一样的可怜的开发者,他们设法创建了一个项目,其中包含大量的音频剪辑,哈哈!

关于javascript - 在 React 中停止路由更改的音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37949895/

相关文章:

html - 如何用html和css实现堆叠样式效果?

javascript - react-router v4 中的 onEnter Prop

javascript - 它如何用 highcharts 实现这个图表?

javascript - View 中的 Backbone 数据逻辑

javascript - 什么是 - function Empty() - 在 javascript 中?

reactjs - Electron、React 和 WebSockets 导致 WebSocket.Server 不是构造函数

reactjs - 解析错误: Unexpected token const

reactjs - 如何正确地将 ReactJS 应用程序部署为 Azure Web 应用程序

javascript - 无法显示使用 templateResult select2 选择的选项

javascript - 如何在 Azure DevOps 发布期间转换/修改 js 文件