簡體   English   中英

ReferenceError:窗口未在打字稿中定義

[英]ReferenceError: window is not defined in typescript

我正在制作一個條形碼掃描儀來掃描 code128 和 pdf417,我正在使用 react-qr-barcode-scanner 在打字稿中這樣做。 但是在運行代碼時出現此錯誤:

Server Error
ReferenceError: window is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.

這是我的代碼:(ScannerTest.tsx)

import { useState } from 'react';
import BarcodeScannerComponent from 'react-qr-barcode-scanner';


export const ScannerTest = () => {
    const [camera, setCamera] = useState(false);
    const [data, setData] = useState("Not Found");
    return (
        <div >
            <div>SCANNER!</div>
            <button onClick={() => setCamera(!camera)}>
                {camera ? "Stop" : "Start"}
            </button>
            <div className="container">
                {camera &&
                    <div>
                        <BarcodeScannerComponent
                            width={500}
                            height={500}
                            onUpdate={(err, result) => {
                                if (result) {
                                    setData(result?.text)
                                }
                            }}
                        />
                        <p>{data}</p>
                    </div>}
            </div>
        </div>
    );
}

export default ScannerTest;

我怎樣才能避免這個錯誤?

這看起來像是 Next.js 錯誤。 您的 React 應用程序是在 NodeJS 環境中的服務器端構建的,其中window對象不存在。 您最早可以訪問window是在效果掛鈎或生命周期方法中:

console.log(window) // undefined

React.useEffect(() => {
  console.log(window); // defined
}, []);

如果在某些庫組件中訪問window對象超出您的控制范圍,那么您需要防止包含它的任何內容被呈現,直到您知道您處於瀏覽器環境中(即標記已被水合):

const useHydrated = () => {
  const [hydrated, setHydrated] = React.useState(false);
  
  React.useEffect(() => {
    setHydrated(true);
  }, []);

  return hydrated;
};

在您的組件中:

const hydrated = useHydrated();

return hydrated ? (
  <div>
    ...
  </div>
) : null;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM