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

大家。我还在习惯 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 的逻辑,但没有一个能达到目的。到目前为止,我已经尝试在 componentWillReceivePropscomponentWillUpdatecomponentDidUpdatecomponentWillUnmounthandleStop/.

我得到的最接近的是在 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>

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

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

https://stackoverflow.com/questions/37949895/

相关文章:

php - 如何在 php 中使用 in_array 并将数组作为针,但在至少有一个值匹配时返回 t

php - Eloquent 模型添加没有 "created_at"和 "updated_at"字段

macos - 通过 PIP 安装 NPM,但得到 "npm: command not found"

assembly - GDB - 它如何知道函数调用堆栈?

python - Sqlalchemy,递归获取具有关系的子项和祖先

javascript - 元素 innerHTML 摆脱事件监听器

angularjs - 具有自动完成功能的 Angular 下拉菜单

Neo4j - 根据关系属性查找两个节点之间的最短路径

r - 如何使用来自多个其他列的所有非 NA 值创建新列?

git - 从 merge 请求创建补丁