我在这个组件中对音频使用react-native-sound,并希望从传递给该组件的url文件中播放。问题是,如果在函数组件中声明了var音频,那么每次组件呈现时,都会再次创建变量,这会将声音文件作为新实例播放,并且我们会在彼此的顶部多次播放相同的声音。
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音频作为全局变量移动到函数组件的外部/上方,它工作得很好,但是我无法将组件属性传递给它,因为该变量超出了函数组件的作用域。我如何传递一个保持引用的道具,而不是在每次渲染时重新创建?
发布于 2021-10-28 04:54:42
尝试使用useEffect:
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.:这段代码是即时编写的,因此可能需要进一步修改
发布于 2021-10-28 05:08:31
这是useRef (https://reactjs.org/docs/hooks-reference.html#useref)的正确用例
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
}
})
}
}, [])发布于 2021-10-28 04:46:09
例如
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]);https://stackoverflow.com/questions/69748380
复制相似问题