我正在尝试构建自己的Gatsby网站以部署到生产环境,但是我遇到了一个问题,我认为该问题与应用程序中的一行代码有关,在该行中,我使用window
重定向到外部网址这是从单击按钮时发出的GET请求中检索到的。我尝试通读documentation on this issue,并尝试有条件地使用它们的窗口检查,但是我的重定向不起作用或收到与Can't resolve 'module'
相关的错误。是否有替代的方法要么全部替换掉window
的使用,要么解决为什么在构建过程中运行failed Building static HTML for pages - 2.611s
ERROR #95312
"window" is not available during server side rendering.
并导致错误?
错误:
WebpackError: ReferenceError: window is not defined
检查窗口代码的错误:
authClick(e) {
e.preventDefault();
this.setState({ authorizing: true }, ()=> {
axios.get(auth_url)
.then((res) => {
this.setState({
authorizing: false
})
window.location.replace(res.data) // Window call
// Attempt to fix the issue based on documentation
// if (typeof window !== `undefined`){
// const module = require("module")
// window.location.replace(res.data)
// }
}).catch((err) => {
console.log(err)
})
});
}
// Component
<button className="inline-flex items-center" onClick={this.authClick} disabled={this.state.authorizing}>
Auth
</button>
代码:
select * from TIFX_CM_MENU_MAIN t1 where function='User Profile' and t1.PARENTID in
(select t2.FUNCTIONID from TIFX_CM_MENU_MAIN t2 where t2.function='Admin' and t2.PARENTID in
(select t3.FUNCTIONID from TIFX_CM_MENU_MAIN t3 where t3.function='WareHouse Operator')) ;
答案 0 :(得分:1)
const isBrowser = () => typeof window !== "undefined"
isBrowser() && window.location.replace(res.data)
如果要使用window.location,则必须先检查然后使用isBrowser() && window.location.replace(res.data)
的{{1}}
答案 1 :(得分:0)
如果您不需要基于window
可用性的任何模块,请不要这样做。就您而言,您只需要进行重定向,而无需导入任何模块。
只是:
authClick(e) {
e.preventDefault();
this.setState({ authorizing: true }, ()=> {
axios.get(auth_url)
.then((res) => {
this.setState({
authorizing: false
})
if (typeof window !== `undefined`){
window.location = res.data
}
}).catch((err) => {
console.log(err)
})
});
}
请注意使用window.location
进行重定向的更改,但是您也可以根据需要使用window.location.replace
。
答案 2 :(得分:0)
文档链接正确无误,因为在构建过程中没有可用的窗口,因此您必须定义检查。
文档中的术语模块将由您所引用的模块的实际名称代替。然后,您将按照文档中提到的窗口检查包装导入/请求。
出于您的目的,代码如下所示:
...
if (typeof window !== `undefined`){
window.location.replace(res.data) // Window call
}
...
由于您不导入模块,因此不需要require模块。
希望如此。
答案 3 :(得分:0)
提示:输入 typeof window !== 'undefined' && window.whaterver-you-need
来解决这个问题。