我在此组件中使用 react-native-sound
来播放音频,并希望从传递给该组件的 url 文件中播放。问题是,如果 var audio 在功能组件内部声明,那么每次组件渲染时都会再次创建变量,这会将声音文件作为新实例播放,并且我们会在彼此之上多次播放相同的声音。
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 audio 作为全局变量移到功能组件之外/上方,它可以正常工作,但是我无法将组件 prop 又名 url
传递给它,因为该变量不在函数中组件范围。如何传递一个保留引用且不会在每次渲染时重新创建的 Prop ?
最佳答案
尝试使用 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.:此代码是即时编写的,因此可能需要进一步修改
关于javascript - 功能性 React 组件中的全局作用域 prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69748380/