Next.js TypeScript "window" is not defined.

3

你好,我这样声明音频上下文:window.Context = window.AudioContext || window.webkitAudioContext;但是它显示窗口未定义。我尝试在window.Context上面声明declare const window: any,但仍然出现错误。有人知道我该如何解决这个问题吗?

window.AudioContext = window.AudioContext || (window as any).webkitAudioContext

export default function TestPage(){

   const audioContext = new AudioContext();

   return <>Hello</>
}

这个回答是否解决了你的问题?在 Next.js React 应用中 "Window is not defined" - juliomalves
2个回答

1

next.js 运行在服务器端。 window 只能在客户端使用。所以你必须等待组件挂载,像这样:



export default function TestPage(){

   const audioContext = useState(null);
   useEffect(() => {
window.AudioContext = window.AudioContext || (window as any).webkitAudioContext;
audioContext.current = new AudioContext();

   },[]);


   return <>Hello</>
}


1
由于服务器端渲染,当Next.js在服务器上进行渲染时,window尚不存在,因为window仅存在于客户端。
我通常的做法是编写一些在客户端触发初始化window的函数:
(我假设您正在使用ReactJS,因为代码片段中有组件格式和片段)
export default function TestPage() {
   const [audioContext, setAudioContext] = useState<AudioContext | null>(null)
   useEffect(() => {
    if (typeof window !== 'undefined') {
      const val = window.AudioContext = window.AudioContext || window.webkitAudioContext;
      setAudioContext(val)
      // or you can put your logic here without setting the state
    }

   }, [])

   useCallback(() => {
     if (audioContext !== null) {  
       const audioContext = new audioContext();
       // your other logic for audio context
     }

   }, [audioContext ])

   return <>Hello</>
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接