3

I've created a very simple Next.js-project with two pages.

Both pages include a basic layout component:

// Page Component  

render() {
  return (
    <PageLayout>
      This is page A
    </PageLayout>
  );
}

And PageLayout looks something like this:

// PageLayout

render() {
  return (
    <div>
      <Header />
      {this.props.children}
    </div>
  );
}

So both pages use PageLayout to render a basic template that also includes the same Header on both pages.

My problem is that the Header component is re-created when navigating between the two pages. I think this is bad not only from a performance point of view, but also because in this case all DOM-Nodes and all React components loose their local state.

So I would like to know if there is something I am missing or how we can create shared components between pages that are reused properly (at least if their state did not change, of course).

4

2 回答 2

2

您有两个具有共同组件的页面:

页面A

<A>
  <Common />
</A>

B页

<B>
  <Common />
</B>

从反应文档

每当根元素具有不同的类型时,React 都会拆除旧树并从头开始构建新树。从<a>to <img>,或 from <Article>to <Comment>,或 from <Button>to <div>——其中任何一个都将导致完全重建。

这就是为什么您会丢失 Common (Header) 组件中的状态。就像我在评论中建议的那样,您必须使用像 redux 这样的外部状态。

于 2018-04-05T17:31:15.180 回答
1

您必须创建一个名为 layout 的组件

// components/layout.js

import Navbar from './navbar'
import Footer from './footer'

export default function Layout({ children }) {
  return (
    <>
      <Navbar />
      <main>{children}</main>
      <Footer />
    </>
  )
}

然后像这样敲击你的 _app.js 组件

// pages/_app.js

import Layout from '../components/layout'

export default function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  )
}

更多阅读https://nextjs.org/docs/basic-features/layouts

于 2021-12-13T10:50:58.627 回答