我认为音频对象在盖茨比上构建时抛出了ReferenceError,我真的不知道为什么。我读过它可能是因为Node.JS,所以我猜我创建音频对象的方式是不正确的。但是,开发版本完全可以正常工作。这是我创建音频对象的组件:
const Button = value => {
const [play, setPlay] = useState(false);
//Switch state
const switchit = () => {setPlay(!play)}
//Getting track info
const track = value.value
const trackName = track && track.name ? track.name : null;
const trackPath = track && track.publicURL ? track.publicURL : null;
//Making track playable
const playAudio = new Audio(trackPath)
const playSound = () => {
if (play === false) {
playAudio.play();
switchit()
setTimeout(() => {
setPlay(false)
}, playAudio.duration * 1000);
} else {}
}
return (
<>
<ButtonStyle onClick={playSound}>{trackName}</ButtonStyle>
</>
)
}
export default Button
这是当我尝试构建项目时抛出的错误:
ERROR
Page data from page-data.json for the failed page "/": {
"componentChunkName": "component---src-pages-index-js",
"path": "/",
"result": {
"pageContext": {}
},
"staticQueryHashes": [
"3649515864",
"3652344105",
"63159454"
]
}
failed Building static HTML for pages - 3.380s
ERROR #95313
Building static HTML failed for path "/"
See our docs page for more info on this error: https://gatsby.dev/debug-html
WebpackError: ReferenceError: Audio is not defined
- index.js:15
webpack:/facusounds/src/components/Button/index.js:15:21
- index.js:22
[facusounds]/[decode-uri-component]/index.js:22:1
- index.js:25
[facusounds]/[decode-uri-component]/index.js:25:1
- index.js:31
[facusounds]/[decode-uri-component]/index.js:31:1
- index.js:30
[facusounds]/[decode-uri-component]/index.js:30:4
- index.js:41
[facusounds]/[decode-uri-component]/index.js:41:1
- static-entry.js:294
webpack:/facusounds/.cache/static-entry.js:294:22
- dev-404-page.js:15
facusounds/.cache/dev-404-page.js:15:11
Gatsby试图访问Audio
对象,该对象仅在客户端可用。您需要添加一些条件逻辑来检查全局window
对象的可用性。
const [playAudio] = useState(window !== 'undefined' ? new Audio(trackPath) : null)
如果你需要在trackPath
变化时更新Audio
对象,你可以使用useEffect
,它只运行客户端(所以不需要窗口检查):
const [playAudio, setAudio] = useState(null)
useEffect(() => {
setAudio(new Audio(trackPath))
}, [trackPath])