1 回答

TA貢獻1877條經驗 獲得超6個贊
請記住,您的函數體中的所有內容都將在每次渲染上運行 - 因此在這種情況下,您正在創建一個新的soundObject并可能soundObject.loadAsync在每個渲染上運行調用。您需要利用其他鉤子來避免這種情況 - 在您的情況下可能useRef和useEffect. 我建議通過 hooks api 參考熟悉這些:https : //reactjs.org/docs/hooks-reference.html
這是我如何避免不必要的影響的快速嘗試。您可能想要查看和調整依賴項數組,具體取決于您希望事情如何運作以及您希望何時重新運行各種效果。例如,我不確定您是否需要Sound重新創建對象。
import React, { useState, useRef, useCallback, useEffect} from 'react';
import { Audio } from 'expo-av';
import { Button, View, Text } from 'react-native';
const AudioPlayer = ({ user }) => {
const [currentProgress, setCurrentProgress] = useState(0);
const soundObjectRef = useRef(new Audio.Sound());
useEffect(() => {
const playbackUpdate = (playbackObject) => {
setCurrentProgress(playbackObject.currentMillis);
// updating state with progress through audio file in milliseconds
}
soundObjectRef.current.setOnPlaybackStatusUpdate(playbackUpdate);
}, []); // do this only once per component mount
// sets a function that is called every 500 milliseconds as the audio is played
useEffect(() => {
if (user) {
soundObjectRef.current.loadAsync({user.message.path});
}
}, [user]); // run this anytime user changes but do not run again if user doesn't change
const play = () => {
soundObjectRef.current.playAsync();
}
return (
<View>
<Text>{currentProgress}</Text>
<Button title="play" onPress={play} />
</View>
)
}
export default AudioPlayer
添加回答
舉報