服务器端渲染构建错误期间 Gatsby 窗口不可用

cph*_*ill 12 javascript reactjs gatsby

我正在尝试构建我的 Gatsby 站点以部署到生产环境,但我遇到了一个问题,我认为该问题与我的应用程序中的一行代码有关,我使用该代码window重定向到从发出的 GET 请求中检索的外部 URL单击按钮。我尝试阅读有关此问题的文档,并尝试使用他们的窗口检查条件,但我的重定向要么不起作用,要么收到与Can't resolve 'module'. 是否有其他方法可以替换全部的使用window或修复在构建期间运行并导致错误的原因?

错误:

failed Building static HTML for pages - 2.611s

 ERROR #95312

"window" is not available during server side rendering.
Run Code Online (Sandbox Code Playgroud)

窗口代码检查错误:

  WebpackError: ReferenceError: window is not defined
Run Code Online (Sandbox Code Playgroud)

代码:

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>
Run Code Online (Sandbox Code Playgroud)

Dip*_*kap 13

const isBrowser = () => typeof window !== "undefined"
isBrowser() && window.location.replace(res.data)
Run Code Online (Sandbox Code Playgroud)

如果你想使用 window.location 那么你必须先检查然后使用它isBrowser() && window.location.replace(res.data)代替window.location.replace(res.data)