我認為在 Gatsby 上構建音頻物件時會拋出 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
uj5u.com熱心網友回復:
Gatsby 正在嘗試訪問該Audio物件,該物件僅在客戶端可用。您需要添加一些條件邏輯來檢查全域window物件的可用性。
const [playAudio] = useState(window !== 'undefined' ? new Audio(trackPath) : null)
如果您需要在更改Audio時更新物件trackPath,您可以使用useEffect僅在客戶端運行的物件(因此不需要視窗檢查):
const [playAudio, setAudio] = useState(null)
useEffect(() => {
setAudio(new Audio(trackPath))
}, [trackPath])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/482257.html
標籤:javascript 反应 网页包 盖茨比 参考错误
上一篇:我的React18的Webpack配置顯示UncaughtTypeError:Failedtoresolvemodulespecifier"react-dom/client"
下一篇:當我嘗試使用near-api-js和webpack5中的keyStores時,為什么會看到“TypeError:str.splitisnotafunction”?
