在我的 Next.js 应用程序中,我似乎无法访问 window
:
未处理的拒绝(ReferenceError):未定义窗口
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
原文由 Leon Gaban 发布,翻译遵循 CC BY-SA 4.0 许可协议
在我的 Next.js 应用程序中,我似乎无法访问 window
:
未处理的拒绝(ReferenceError):未定义窗口
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
原文由 Leon Gaban 发布,翻译遵循 CC BY-SA 4.0 许可协议
̶A̶n̶o̶t̶h̶e̶r̶ ̶s̶o̶l̶u̶t̶i̶o̶n̶ ̶i̶s̶ ̶b̶y̶ ̶u̶s̶i̶n̶g̶ ̶ p̶r̶o̶c̶e̶s̶s̶.̶b̶r̶o̶w̶s̶e̶r
̶ ̶t̶o̶ ̶j̶u̶s̶t̶ ̶e̶x̶e̶c̶u̶t̶e̶ ̶ ̶y̶o̶u̶r̶ ̶c̶o̶m̶m̶a̶n̶d̶ ̶d̶u̶r̶i̶n̶g̶ ̶r̶e̶n̶d̶e̶r̶i̶n̶g̶ ̶o̶n̶ ̶t̶h̶e̶ ̶c̶l̶i̶e̶n̶t̶ ̶s̶i̶d̶e̶ ̶o̶n̶l̶y̶.
但是 process
对象在 Webpack5 和 NextJS 中已被弃用,因为它是仅用于后端的 NodeJS 变量。
所以我们必须使用来自浏览器的 back window
对象。
if (typeof window !== "undefined") {
// Client-side-only code
}
其他解决方案是使用 react hook 替换 componentDidMount
:
useEffect(() => {
// Client-side-only code
})
原文由 Darryl RN 发布,翻译遵循 CC BY-SA 4.0 许可协议
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
将代码从
componentWillMount()
移动到componentDidMount()
:在 Next.js 中,
componentDidMount()
仅在可以使用window
和其他浏览器特定 API 的客户端上执行。从 Next.js 维基:同样,
componentWillMount()
将在 React v17 中被 弃用,因此在不久的将来使用它实际上可能是不安全的。