首页 > 解决方案 > 执行上下文被破坏,很可能是因为导航

问题描述

当我为我的 React 应用程序进行生产构建时,会出现此错误。发生这种情况是因为我有一个脚本可以检测浏览器的语言并将用户重定向到使用他们的语言的网站版本。

这是有问题的代码(在 App.js 中):

useEffect(() => {
  let navLang = navigator.language || navigator.userLanguage;
  navLang = navLang.split("-");
  let myLang = navLang[0];

  let fullPathname = window.location.pathname;
  fullPathname = fullPathname.toLowerCase();
  let newPathname = fullPathname.split("/")

  // If the site is already in the browser's language stop the function
  if(myLang === newPathname[1] || (newPathname[1] === "jp" && (myLang === "ja" || myLang === "jpn"))) {
    return
  } else {
    // get the pathname without the language
    // i.e if the url is "/en/profile/" the output will be /profile" 
    let pathname = getPathname(fullPathname)

    
    if(myLang === "es" || myLang === "spa") {
      window.location.pathname = "/es/" + pathname;
    } else if(myLang === "ja" || myLang === "jpn") {
      window.location.pathname = "/jp/" + pathname;
    } else {
      window.location.pathname = "/en/" + pathname;
    }
  }
}, [])

如果我理解正确,问题是 react-snap 在抓取页面时,这段代码有问题。

如果您想知道为什么我使用它window.location.pathname而不是history.replace()它是因为其他一些原因,现在不值得解释。

标签: javascriptreactjsreact-snap

解决方案


推荐阅读