我有一个页面/trial
,我想确保始终使用路由参数对其进行访问。 在我的构造函数中,我检查this.props.location.search
,如果它是虚假的(空),我想导航到/trial/?product=foobar
。
这是我的代码
import React from 'react'
import { navigate } from 'gatsby'
class Foobar extends React.Component {
constructor(props) {
super(props)
this.redirectIfNecessary()
}
redirectIfNecessary() {
// Make prospect the default product
const { location } = this.props
const { search } = location
if (!search) {
navigate('/trial/?product=foobar', {
state: {
product: 'foobar',
},
})
}
}
render() {
return <div>Hello, world</div>
}
}
这在开发期间可以正常工作,但是当我运行gatsby build
我得到了
error Building static HTML for pages failed
See our docs page on debugging HTML builds for help https://goo.gl/yL9lND
186 |
187 | var navigate = function navigate(to, options) {
> 188 | window.___navigate(withPrefix(to), options);
| ^
189 | };
190 |
191 | exports.navigate = navigate;
WebpackError: ReferenceError: window is not defined
gatsby info --clipboard
System:
OS: macOS 10.14.1
CPU: (12) x64 Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
Shell: 5.3 - /bin/zsh
Binaries:
Node: 11.3.0 - /usr/local/bin/node
Yarn: 1.12.3 - /usr/local/bin/yarn
npm: 6.4.1 - /usr/local/bin/npm
Browsers:
Chrome: 70.0.3538.110
Firefox: 63.0.3
Safari: 12.0.1
npmPackages:
gatsby: ^2.0.64 => 2.0.64
gatsby-image: ^2.0.20 => 2.0.22
gatsby-plugin-manifest: ^2.0.10 => 2.0.11
gatsby-plugin-offline: ^2.0.19 => 2.0.19
gatsby-plugin-react-helmet: ^3.0.4 => 3.0.4
gatsby-plugin-react-svg: ^2.0.0 => 2.0.0
gatsby-plugin-sass: ^2.0.7 => 2.0.7
gatsby-plugin-sharp: ^2.0.15 => 2.0.15
gatsby-source-filesystem: ^2.0.11 => 2.0.11
gatsby-transformer-sharp: ^2.1.8 => 2.1.9
npmGlobalPackages:
gatsby-cli: 2.4.6
嘿@kevinmichaelchen
Webpack无法构建它,因为window
仅在浏览器中可用,而在构建期间不可用。
您可以通过将redirectIfNecessary
调用从constructor
移至componentDidMount
来解决此问题。 这样,它将仅在客户端运行,而不在构建期间运行。
您还可以在渲染功能中以声明方式执行此操作,方法是包括来自到达路由器的
我现在要关闭此问题,因为此问题并非特定于盖茨比,但如有其他问题,请随时重新打开。
用户浏览器monads repo作为对此的快速解决方案!
最有用的评论
嘿@kevinmichaelchen
Webpack无法构建它,因为
window
仅在浏览器中可用,而在构建期间不可用。您可以通过将
redirectIfNecessary
调用从constructor
移至componentDidMount
来解决此问题。 这样,它将仅在客户端运行,而不在构建期间运行。您还可以在渲染功能中以声明方式执行此操作,方法是包括来自到达路由器的
我现在要关闭此问题,因为此问题并非特定于盖茨比,但如有其他问题,请随时重新打开。