[英]How can I use getInitialProps only during the NextJS site build?
[英]Nextjs getInitialProps error preventing build on Netlify
嘿伙計們,我繼承了一個用 nextjs 構建並在 Netlify 上運行的項目。 我正在嘗試在用戶使用 IE 時加載組件。 在本地,我可以毫無問題地渲染組件視圖。 但是當構建運行(代碼推送到特定分支)時,構建在 Netlify 上失敗。 Netlify 似乎不喜歡以下內容。
const userAgent = props ? props.req.headers['user-agent'] : navigator.userAgent
接受任何建議。 我是 Netlify 的新手,只是試圖顯示一個讓用戶知道他們的瀏覽器不受支持的組件。 下面是我在 _document.js 中的代碼
_document.js
class MyDocument extends Document {
static async getInitialProps(props) {
const page = props.renderPage()
const userAgent = props ? props.req.headers['user-agent'] : navigator.userAgent
return {
...page,
userAgent
}
}
renderBrowserSupport() {
let msie = this.props.userAgent.indexOf('MSIE ');
let ie11 = this.props.userAgent.indexOf('Trident/');
if(msie > 0 || ie11 > 0) {
return (
<BrowserSupport/>
)
}
else return false;
}
render() {
<html lang="en">
<body>
{this.renderBrowserSupport()}
</body>
</html>
}
}
export default MyDocument
運行 npm 運行構建時出錯
Cannot read property 'user-agent' of undefined
我在向 _document.js 添加代碼時遇到了幾個問題,所以我采用了不同的方法,如下所示:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.