【问题标题】:ReferenceError: window is not defined w/ useMedia() hook + next.jsReferenceError:未使用 useMedia() hook + next.js 定义窗口
【发布时间】:2020-05-06 16:55:48
【问题描述】:

因为我使用的是 next.js,所以我认为由于代码在服务器端而不是在客户端执行,我收到了“未定义窗口”错误。我尝试使用 useLayoutEffect() 来等待页面呈现,但它仍然不起作用。我可以做些什么来更改下面的自定义 useMedia() 挂钩来解决此问题?

export default (queries, values, defaultValue) => {
  const mediaQueryLists = queries.map(q => window.matchMedia(q));

  const getValue = () => {
    const index = mediaQueryLists.findIndex(mql => mql.matches);

    return typeof values[index] !== "undefined" ? values[index] : defaultValue;
  };

  const [value, setValue] = useState(getValue);
  useEffect(() => {
    const handler = () => setValue(getValue);

    mediaQueryLists.forEach(mql => mql.addListener(handler));

    return () => mediaQueryLists.forEach(mql => mql.removeListener(handler));
  }, []);

  return value;
};

【问题讨论】:

    标签: javascript reactjs react-hooks next.js server-side-rendering


    【解决方案1】:

    因为窗口没有按时挂载尝试等待它使用:

    let mediaQueryLists
    if (typeof window !== 'undefined') {
      mediaQueryLists = queries.map(q => window.matchMedia(q));
    } else {
      mediaQueryLists = []
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 2022-01-18
      • 2021-10-06
      • 2022-01-21
      • 2021-03-30
      • 2020-10-08
      • 2018-05-27
      • 2020-09-18
      • 1970-01-01
      相关资源
      最近更新 更多