在 Next.js 中根据屏幕尺寸呈现不同的组件

Render different components based on screen size in Next.js

我正在尝试根据屏幕宽度 < 768p 以不同方式渲染渲染组件。

如果小于768p,则加载汉堡菜单。如果没有,加载整个菜单。

这是我使用的代码。问题是,当页面首次加载时,我无法观察到变化。但是当我将浏览器屏幕变小然后将其增加到原来的大小时;效果发生了。

我认为这是因为 React 正在服务器端呈现。但是还是不明白为什么要把屏幕先变小再变大。

import "twin.macro"
import { Global, css } from "@emotion/core"

import { useState, useEffect } from "react"

const Navbar = () => {
  const useWindowDimensions = () => {
    const hasWindow = typeof window !== "undefined"

    function getWindowDimensions() {
      const width = hasWindow ? window.innerWidth : null
      const height = hasWindow ? window.innerHeight : null
      return {
        width,
        height,
      }
    }

    const [windowDimensions, setWindowDimensions] = useState(
      getWindowDimensions()
    )

    useEffect(() => {
      if (hasWindow) {
        function handleResize() {
          setWindowDimensions(getWindowDimensions())
        }

        window.addEventListener("resize", handleResize)
        return () => window.removeEventListener("resize", handleResize)
      }
    }, [hasWindow])

    return windowDimensions
  }

  const { height, width } = useWindowDimensions()
  const breakpoint = 768

  return (
    <div>
      {width <= breakpoint ? (
        <div>
          <HamburgerMenu />
        </div>
      ) : (
        <div>
           <FullMenu />
        </div>
  )
}

export default Navbar

有什么方法可以强制 Next.js 应用在第一次渲染时应用效果?

Next.js 是通用的,这意味着它首先在服务器端执行代码,然后在客户端执行。 window 对象仅存在于客户端

所以第一次访问不到window,所以windowDimensions的值为null

当你调整大小时改变状态让你的应用重新渲染,所以它变成客户端渲染=>你可以访问window,然后你的代码工作