【问题标题】:Next.js typescript "window" in not definedNext.js 打字稿“窗口”未定义
【发布时间】:2022-02-02 13:47:53
【问题描述】:

您好,我正在声明一个像这样的音频上下文,它说窗口未定义。我尝试在 window.Context 上方声明 declare const window :any 但错误仍然存​​在。有谁知道我该如何解决这个问题?

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

export default function TestPage(){

   const audioContext = new AudioContext();

   return <>Hello</>
}

【问题讨论】:

标签: typescript next.js


【解决方案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</>
}

【讨论】:

    【解决方案2】:

    这是因为服务端渲染,所以当nextjs在服务端渲染时window还不存在,因为window只在客户端。

    我通常做的是在客户端触发某种函数来初始化窗口:

    (由于sn-p上的组件格式和片段,我假设您使用的是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</>
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-06
      • 1970-01-01
      • 2021-09-19
      • 2019-07-04
      • 2020-05-06
      • 1970-01-01
      • 2021-10-26
      相关资源
      最近更新 更多