我试图在我的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提供的<Component/>应该与报头一起呈现的地方)
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>
}发布于 2022-01-02 00:06:24
在React框架中,调用组件函数并不一定再次呈现HTML。如果您不希望调用header函数,或者不希望它返回的vdom在页面更改上有所差异,那么将标题备注是有意义的。
const HeaderMemo = React.memo(Header);
// in the layout
<HeaderMemo user={user} />https://stackoverflow.com/questions/70551919
复制相似问题