簡體   English   中英

ReferenceError: window 未在 NextJs 上定義

[英]ReferenceError: window is not defined on NextJs

嘗試從“react-facebook-pixel”導入 ReactPixel; 但是當我拋出一個參考錯誤時,說 window 沒有定義。

 module.exports = require("react-facebook-pixel");

是我導入 ReactPixel 時遇到問題的特定代碼行。

我猜你正在導入 facebook-pixel,就好像它在客戶端而不是 ssr(即 NextJS)上運行一樣。 一旦您的組件在客戶端加載,您將需要動態重要:

https://github.com/zsajjad/react-facebook-pixel/issues/53

使用任一 useEffect:

  React.useEffect(() => {
    import("react-facebook-pixel")
      .then((x) => x.default)
      .then((ReactPixel) => {
        ReactPixel.init(constants.siteMeta.FacebookPixelID);
        ReactPixel.pageView();

        Router.events.on("routeChangeComplete", () => {
          ReactPixel.pageView();
        });
      });
  });

或 componentDidMount()

export default class App extends NextApp {
  componentDidMount() {
    import('react-facebook-pixel')
      .then((x) => x.default)
      .then((ReactPixel) => {
        ReactPixel.init('your-pixel-id');
        ReactPixel.pageView();

        Router.events.on('routeChangeComplete', () => {
          ReactPixel.pageView();
        });
      });
  }
}

暫無
暫無

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

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