我需要访问我的react组件中的window
对象以从查询字符串中获取一些信息。这是我的组件的样子:
export function MyComponent() {
return (
<div>
Display the qs: {(window && window.location.search) || 'nothing'}
</div>
)
}
如果我运行该应用程序然后访问需要访问该窗口的页面,这一切都很好,但是如果我在需要该窗口的页面上启动该应用程序,则会出现以下错误:
ReferenceError:未定义窗口
到目前为止,我看到的大多数解决方案都利用componentWillMount
来解决此问题。所以我的问题是,如何在功能组件中解决此问题?还是不使用生命周期方法的最佳方法是什么?
不确定这是否相关,但我也正在使用NextJS。
答案 0 :(得分:4)
请参阅Next.js wiki
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>;
}
答案 1 :(得分:2)
const isWindowContext = typeof window !== "undefined";
export function MyComponent() {
const search = isWindowContext && window.location.search;
return <div>Display the qs: {search || 'nothing'}</div>;
}