the*_*uls 2 javascript reactjs next.js
我需要访问window
我的反应组件中的对象以从查询字符串中获取一些东西。这是我的组件的样子:
export function MyComponent() {
return (
<div>
Display the qs: {(window && window.location.search) || 'nothing'}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
如果我运行应用程序然后访问我需要访问窗口的页面,这一切都很好,但是如果我在需要窗口的页面上启动应用程序,我会收到以下错误:
参考错误:窗口未定义
到目前为止,我看到的大多数解决方案都使用componentWillMount
来解决问题。所以我的问题是,如何在功能组件中解决这个问题?或者在不使用生命周期方法的情况下这样做的最佳方法是什么?
不确定这是否相关,但我也在使用 NextJS。
Next.js 是通用的,这意味着它首先在服务器端执行代码,然后在客户端执行。window 对象仅存在于客户端,因此如果您绝对需要在某些 React 组件中访问它,您应该将该代码放在 componentDidMount 中。这个生命周期方法只会在客户端执行。您可能还想检查是否没有适合您需要的替代通用库。
export function MyComponent() {
const isAvailable = useRef(false);
useEffect(() => {
isAvailable.current = typeof window !== "undefined" && window.location.search;
}, []);
return <div>Display the qs: {isAvailable.current || 'nothing'}</div>;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4475 次 |
最近记录: |