如何访问gatsby-theme-material-ui-top-layout中的{window,location}

问题描述 投票:1回答:1

我如何访问gatsby-theme-material-ui-top-layout / components / top-layout中的{window,location}

我必须使用gatsby-plugin-layout吗?

我可以同时使用gatsby-plugin-layout和gatsby-theme-material-ui吗?

reactjs gatsby
1个回答
0
投票

您不需要额外的插件即可。您可以通过多种选择来实现此目的,但是如果没有提供任何代码,就很难猜测哪一个适合您的要求或规格。您可以随时访问window对象,请记住您的代码可能会在build命令上引发错误,因此:

  • 将代码放入componentDidMount生命周期或useEffect挂钩中,以确保代码除非在将要定义window的浏览器中,否则无法运行。
  • 在执行语句之前使用条件:

    if (typeof window !== 'undefined') { //your code here }

  • 另一个选择是您的代码使用了需要预先定义window的第三方模块/库,因此,当Gatsby构建(编译和捆绑)您的所有资产时,您的代码可能会因当时需要满足库的需求以及window对象的定义,在这种情况下,您需要将Webpack加载程序更改为null。在您的gatsby-node.js中:

    exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => { if (stage === "build-html") { actions.setWebpackConfig({ module: { rules: [ { test: /bad-module/, use: loaders.null(), }, ], }, }) } }

© www.soinside.com 2019 - 2024. All rights reserved.