【问题标题】:Issue with window object on a functional react component功能性反应组件上的窗口对象问题
【发布时间】:2023-03-22 04:27:01
【问题描述】:

我需要访问我的 react 组件中的 window 对象以从查询字符串中获取某些内容。这是我的组件的样子:

export function MyComponent() {
  return (
    <div>
      Display the qs: {(window && window.location.search) || 'nothing'}
    </div>
  )
}

如果我运行应用程序然后访问我需要访问窗口的页面,这一切都很好,但是如果我在需要窗口的页面上启动应用程序,我会收到以下错误:

ReferenceError: 未定义窗口

到目前为止,我看到的大多数解决方案都使用componentWillMount 来解决问题。所以我的问题是,如何在功能组件中解决这个问题?或者不使用生命周期方法的最佳方法是什么?

不确定这是否相关,但我也在使用 NextJS。

【问题讨论】:

  • 我认为问题出在服务器端渲染,全局变量window在服务器端不存在
  • 你设置router了吗?

标签: javascript reactjs next.js


【解决方案1】:

参考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>;
}

【讨论】:

    【解决方案2】:
    const isWindowContext = typeof window !== "undefined";
    
    export function MyComponent() {
      const search = isWindowContext && window.location.search;
      return <div>Display the qs: {search || 'nothing'}</div>;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2019-11-09
      • 2021-10-18
      • 2020-12-29
      • 2020-03-18
      • 2018-12-27
      相关资源
      最近更新 更多