在我的 Next.js 应用中,我似乎无法访问window:
window
未处理的拒绝(ReferenceError):未定义窗口
componentWillMount() { console.log('window.innerHeight', window.innerHeight); }
将代码从componentWillMount()移至componentDidMount():
componentWillMount()
componentDidMount()
componentDidMount() { console.log('window.innerHeight', window.innerHeight); }
在Next.js中,componentDidMount()仅在window可使用其他浏览器特定API 的客户端上执行。从Next.js Wiki:
Next.js是通用的,这意味着它首先在服务器端执行代码,然后在客户端执行代码。window对象仅在客户端存在,因此,如果您绝对需要在某些React组件中访问它,则应将该代码放在componentDidMount中。此生命周期方法将仅在客户端上执行。您可能还需要检查是否没有满足您需求的替代通用库。
同样,React v17 componentWillMount()中将弃用该功能,因此在不久的将来使用它实际上将不安全。