功能反应组件上的 window 对象问题
Issue with window object on a functional react component
我需要访问我的 React 组件中的 window
对象以从查询字符串中获取某些内容。这是我的组件的样子:
export function MyComponent() {
return (
<div>
Display the qs: {(window && window.location.search) || 'nothing'}
</div>
)
}
如果我 运行 应用程序然后访问我需要访问 window 的页面,这一切都很好,但是如果我在页面上启动应用程序,我需要 window,我收到以下错误:
ReferenceError: window is not defined
到目前为止我看到的大多数解决方案都使用 componentWillMount
来解决问题。所以我的问题是,如何在功能组件中解决这个问题?或者不使用生命周期方法的最佳方法是什么?
不确定这是否相关,但我也在使用 NextJS。
const isWindowContext = typeof window !== "undefined";
export function MyComponent() {
const search = isWindowContext && window.location.search;
return <div>Display the qs: {search || 'nothing'}</div>;
}
Next.js is universal, which means it executes code first server-side, then client-side. The window object is only present client-side, so if you absolutely need to have access to it in some React component, you should put that code in componentDidMount. This lifecycle method will only be executed on the client. You may also want to check if there isn't some alternative universal library which may suit your needs.
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>;
}
我需要访问我的 React 组件中的 window
对象以从查询字符串中获取某些内容。这是我的组件的样子:
export function MyComponent() {
return (
<div>
Display the qs: {(window && window.location.search) || 'nothing'}
</div>
)
}
如果我 运行 应用程序然后访问我需要访问 window 的页面,这一切都很好,但是如果我在页面上启动应用程序,我需要 window,我收到以下错误:
ReferenceError: window is not defined
到目前为止我看到的大多数解决方案都使用 componentWillMount
来解决问题。所以我的问题是,如何在功能组件中解决这个问题?或者不使用生命周期方法的最佳方法是什么?
不确定这是否相关,但我也在使用 NextJS。
const isWindowContext = typeof window !== "undefined";
export function MyComponent() {
const search = isWindowContext && window.location.search;
return <div>Display the qs: {search || 'nothing'}</div>;
}
Next.js is universal, which means it executes code first server-side, then client-side. The window object is only present client-side, so if you absolutely need to have access to it in some React component, you should put that code in componentDidMount. This lifecycle method will only be executed on the client. You may also want to check if there isn't some alternative universal library which may suit your needs.
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>;
}