繁体   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