/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
window
はブラウザでのみ使用可能であり、ビルド時には使用できないため、Webpackはこれをビルドできません。代わりに、
redirectIfNecessary
呼び出しをconstructor
からcomponentDidMount
に移動することで、これを修正できます。 そうすれば、ビルド時にではなく、クライアント側でのみ実行されます。リーチルーターからのます
この問題はギャツビーに固有のものではないため、今のところこれを閉じていますが、他に何かあればお気軽に再開してください。