useEffect没有持续发射



组件正在3D场景中创建一个positionalAudio,音频对象可以通过使用leva进行调整。对象的创建方式与它应该创建的一样,调整位置和旋转也很好。无法正常工作的是更改音量。在leva UI中,我可以拖动卷的句柄进行更改,但没有发生任何效果(我认为这是因为useEffect在句柄释放之前就启动了,实际上值还没有发生任何更改。在我释放句柄之前,至少会显示控制台日志(。当我在输入字段中输入新值时,按下回车键useEffect,音量也在变化。但它只在这一次起作用,之后就不再起作用了。

import * as THREE from 'three'
import React, { Suspense, useRef, useEffect, useState } from 'react'
import { useThree, useLoader } from '@react-three/fiber'
import { PositionalAudioHelper } from 'three/examples/jsm/helpers/PositionalAudioHelper.js'
import { useControls } from 'leva'
function Sound({ url, volume }) {
const sound = useRef()
const { camera } = useThree()
const [listener] = useState(() => new THREE.AudioListener())
const buffer = useLoader(THREE.AudioLoader, url)
useEffect(() => {
sound.current.setBuffer(buffer)
sound.current.setRefDistance(1)
sound.current.setRolloffFactor(0)
sound.current.setDirectionalCone(180, 230, 0.1)
sound.current.setLoop(true)
sound.current.play()
const helper = new PositionalAudioHelper(sound.current)
sound.current.add(helper)
camera.add(listener)
return () => camera.remove(listener)
}, [])
useEffect(() => {
sound.current.setVolume(volume)
}, [sound.current])
return (
<positionalAudio ref={sound} args={[listener]} />
)
}
export default function App({ url, position}) {
const { posXRight, posYRight, posZRight, rotationYRight, volumeRight } = useControls({
posXRight: {
value: position[0],
min: -20,
max: 20,
step: 1
},
posYRight: {
value: position[1],
min: -20,
max: 20,
step: 1
},
posZRight: {
value: position[2],
min: -20,
max: 20,
step: 1
},
rotationYRight: {
value: 0,
min: 0,
max: Math.PI * 2,
step: Math.PI * 0.25
},
volumeRight: {
value: 1,
min: 0,
max: 1,
step: 0.05
}
})
return (
<Suspense fallback={null}>
<mesh position={[posXRight, posYRight, posZRight]} rotation={[0, rotationYRight, 0]}>
<sphereGeometry args={[0.1, 32, 32]} />
<meshStandardMaterial color="white" />
<Sound url={url} volume={volumeRight} />
</mesh>
</Suspense>
)
}
useEffect(() => {
sound.current.setVolume(volume)
}, [sound.current])

该挂钩在初始渲染时以及每次sound.current更改时都会触发(可能永远不会(。您应该将其更改为[volume]

最新更新