使用效果内部功能如何先于外部功能执行



下面是https://docs.expo.io/versions/latest/sdk/audio/用于在按下播放按钮时在两个声音之间迭代。

在这个例子中,使用效果负责卸载声音(如果存在的话(。看起来像

React.useEffect(() => {
console.log(`INSIDE: useEffect.`);
return sound
? () => {
console.log('Unloading Sound');
sound.unloadAsync();
}
: undefined;
}, [sound]);

控制台输出看起来像:

--------------------------------------------------------------------------------
Play Button pressed.
Loading Sound
BEFORE: await sound.playAsync()
Unloading Sound
INSIDE: useEffect.
AFTER: await sound.playAsync()

为什么Unloading SoundINSIDE: useEffect.之前?

import * as React from 'react';
import { View, Button } from 'react-native';
import { Audio } from 'expo-av';
import { Sound } from "expo-av/build/Audio/Sound";
const URIS = [
'https://s3.amazonaws.com/exp-us-standard/audio/playlist-example/Podington_Bear_-_Rubber_Robot.mp3',
"https://ia800304.us.archive.org/34/items/PaulWhitemanwithMildredBailey/PaulWhitemanwithMildredBailey-AllofMe.mp3"
]
let uriIndex = 0;

function getUri() {
uriIndex++;
if (uriIndex == URIS.length){
uriIndex = 0;
}
return URIS[uriIndex];
}
export default function SoundApp() {
const [sound, setSound] = React.useState<Sound>();

async function playSound() {
console.log('Loading Sound');
let URI = getUri();
const {sound} = await Audio.Sound.createAsync(
{uri: URI}
);
setSound(sound);
console.log(`BEFORE: await sound.playAsync()`);
await sound.playAsync();
console.log(`AFTER: await sound.playAsync()`);
}
React.useEffect(() => {
console.log(`INSIDE: useEffect.`);
return sound
? () => {
console.log('Unloading Sound');
sound.unloadAsync();
}
: undefined;
}, [sound]);
return (
<View style={{}}>
<Button title="Play Sound" onPress={() => {
console.log(`--------------------------------------------------------------------------------`);
console.log(`Play Button pressed.`);
playSound()
}}/>
<Button title={'STOP'} onPress={
() => {
sound?.unloadAsync();
}
}/>
</View>
);
}

我从您的日志中猜测,该状态中存在以前的"声音",因此在触发新效果之前,会调用旧声音的先前效果清理(您称之为内部函数(。

相关内容

  • 没有找到相关文章

最新更新