我创建了一个非常简单的 Next.js -项目有两页。
两个页面都包含一个基本的布局组件:
// Page Component
render() {
return (
<PageLayout>
This is page A
</PageLayout>
);
}
PageLayout 看起来像这样:
// PageLayout
render() {
return (
<div>
<Header />
{this.props.children}
</div>
);
}
所以两个页面都使用 PageLayout
来呈现一个基本模板,该模板在两个页面上也包含相同的 Header
。
我的问题 是在两个页面之间导航时重新创建了Header
组件。我认为这不仅从性能的 Angular 来看很糟糕,而且因为在这种情况下所有的 DOM 节点和所有的 React 组件都失去了它们的本地状态。
所以我想知道是否有我遗漏的东西,或者我们如何在页面之间创建共享组件,这些组件可以正确重用(当然,至少在它们的状态没有改变的情况下)。
最佳答案
您有两个具有共同组件的页面:
页面A:
<A>
<Common />
</A>
页面B:
<B>
<Common />
</B>
From the React documentation :
Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch. Going from
<a>
to<img>
, or from<Article>
to<Comment>
, or from<Button>
to<div>
- any of those will lead to a full rebuild.
这就是为什么您会丢失 Common (Header) 组件中的状态。就像我在评论中建议的那样,您必须使用像 redux 这样的外部状态。
关于javascript - 下一个 : shared components between pages,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49677936/