首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数式react组件中全局作用域属性

函数式react组件中全局作用域属性
EN

Stack Overflow用户
提问于 2021-10-28 04:38:36
回答 4查看 114关注 0票数 2

我在这个组件中对音频使用react-native-sound,并希望从传递给该组件的url文件中播放。问题是,如果在函数组件中声明了var音频,那么每次组件呈现时,都会再次创建变量,这会将声音文件作为新实例播放,并且我们会在彼此的顶部多次播放相同的声音。

代码语言:javascript
复制
import Sound from "react-native-sound"

var audio = new Sound.. //Works if declared here but cant's pass url prop

const SoundPlayer: FC<SoundProps> = ({ url }) => {
    const [playing, setPlaying] = useState<boolean | null>(null)

    var audio = new Sound(url, null, (error) => {
        if (error) {
            console.log("failed to load the sound", error)
            return
        }
    })

如果我将var音频作为全局变量移动到函数组件的外部/上方,它工作得很好,但是我无法将组件属性传递给它,因为该变量超出了函数组件的作用域。我如何传递一个保持引用的道具,而不是在每次渲染时重新创建?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2021-10-28 04:54:42

尝试使用useEffect:

代码语言:javascript
复制
const audioRef = useRef(null);
const [duration, setDuration] = useState(0);

useEffect(() => {
   // This will be triggered only once when the component is mounted
   audioRef.current = new Sound(url, null, (error) => {
      if(error) {
         // Here you can implement some retry policy if there was some error loading the sound
         return;
      }

      setDuration(Math.trunc(audioRef.current.getDuration())); 
   });

   return = () => {
     // This will be triggered on component is unmounted
     audioRef.current.release();
   }
}, [audioRef, setDuration]);

P.D.:这段代码是即时编写的,因此可能需要进一步修改

票数 1
EN

Stack Overflow用户

发布于 2021-10-28 05:08:31

这是useRef (https://reactjs.org/docs/hooks-reference.html#useref)的正确用例

代码语言:javascript
复制
import Sound from "react-native-sound"

const SoundPlayer: FC<SoundProps> = ({ url }) => {
    const audioRef = useRef(null); 
    const [playing, setPlaying] = useState<boolean | null>(null)

  // use useEffect to hook on mounted
   useEffect(() => {
    if(audioRef.current === null) {
      audioRef.current = new Sound(url, null, (error) => {
        if (error) {
            console.log("failed to load the sound", error)
            return
        }
      })
    }
   }, [])
票数 1
EN

Stack Overflow用户

发布于 2021-10-28 04:46:09

例如

代码语言:javascript
复制
import Sound from "react-native-sound"

var audio;

const SoundPlayer: FC<SoundProps> = ({ url }) => {
    const [playing, setPlaying] = useState<boolean | null>(null)
    
    useEffect(() => {
      audio = new Sound(url, null, (error) => {
          if (error) {
              console.log("failed to load the sound", error)
              return
          }
      })
    }, [url]);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69748380

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档