【问题标题】:Next.js shared component (header) gets rerendered on new routeNext.js 共享组件(标题)在新路由上重新渲染
【发布时间】:2022-01-02 08:06:24
【问题描述】:

我试图在我的 Next.js 应用程序的所有页面之间共享一个标题组件,但是当我尝试使用 Next 的 Link 组件在路由之间导航时,标题会重新呈现。我创建了一个布局组件,它应该与所有可能的路线一起呈现标题。基本上我不希望标题被重新渲染,但使用 Next.js 路由器访问不同的路由它会由于某种原因被重新渲染。

_app.tsx

function MyApp({ Component, pageProps }: AppProps) {
  return <QueryClientProvider client={queryClient}>
            <AuthProvider>
              <LayoutMain>
                <Component {...pageProps} />
              </LayoutMain>
            </AuthProvider>
          </QueryClientProvider> 
}

LayoutMain.tsx (这是我从 _app.tsx 提供的&lt;Component/&gt; 应该与标题一起呈现的地方)

function LayoutMain({children}: {children: React.ReactNode}){
    const {user} = useContext(AuthContext)
    
    if(!user) return <Login/>
 
    return <>
           <Header/>
           {children}
           </>
}

Header.tsx

function Header() {

  console.log('Header rendered')

  const {user} = useContext(AuthContext)

  return <div className="flex w-full border-b-[1px] border-opacity-25 border-black justify-center bg-white">
    <div className="flex justify-between py-2 items-center w-[1000px] my-2 mx-4fvgd">
      <Image className="cursor-pointer" objectFit="cover" src="/iglogo.svg" width="100" height="35"/>
      <input className="border-[1px] hidden md:block bg-[#fafafa] border-gray-600 border-opacity-30 py-1 px-2 rounded-sm" type="text" placeholder="Search"/>
      <div className="flex justify-center gap-5">
        <HomeIcon className="cursor-pointer"/>
        <SearchIcon className="cursor-pointer"/>
        <SendOutlinedIcon  className="cursor-pointer -rotate-45 -translate-y-1"/>
        <AddCircleOutlineIcon className="cursor-pointer"/>
        <FavoriteBorderIcon className="cursor-pointer"/>
        <Link href={`/profile/${user?.id}`}>
          <div ><Image className="rounded-full cursor-pointer" src="/weeknd.png" objectFit="cover" width="22" height="22"/></div>
        </Link>
      </div>
      </div>
  </div>
}

【问题讨论】:

  • 也就是说,改变路由会重新渲染所有组件,包括布局组件。但是,它的状态将保持不变。

标签: reactjs next.js


【解决方案1】:

在 React 框架中,调用组件函数并不一定要再次渲染 HTML。如果您不希望调用 header 函数或它返回的 vdom 在页面更改上获得差异,那么备注 header 是有意义的。

const HeaderMemo = React.memo(Header);

// in the layout
<HeaderMemo user={user} />

【讨论】:

  • 我尝试在备忘录中包含它,但它仍然重新渲染。也许这就是 Next 中路由的工作方式我无法弄清楚
猜你喜欢
  • 2020-07-24
  • 2019-07-22
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 2019-06-04
  • 2014-09-11
  • 2020-08-14
  • 2020-01-02
相关资源
最近更新 更多