防止重新渲染 中的组件

问题描述 投票:0回答:1

我有一个Gatsby网站,该网站返回了Layout.js中的以下模式:>

<div>
 <Header />
 {props.children}
 <Footer />
</div>

在我的所有页面文件(例如index.jsblog.js中,我都将内容包装在Layout组件中,因此页眉和页脚都出现在这两个文件上。

<Layout>
  Some content here
</Layout>

我遇到的问题是Header组件会在每次更改路线时重新渲染,这是我想防止的,因为由于动画而发生的情况非常明显。 Gatsby是否存在第二层,我可以放置HeaderFooter组件,使其位于Layout之外,而新页面内容会重新渲染它们?我尝试将它们包装在root中的html.js元素周围,但这会导致FOUT问题。

我尝试使用此官方插件:https://www.gatsbyjs.org/packages/gatsby-plugin-layout/,并相应地更新了我的index.jsblog.js,以删除包装的Layout组件。我的问题是路由更改根本不再导致Layout重新呈现,因此内容不会更新。

我也尝试过在false中返回shouldComponentUpdate,并尝试将Header组件包装在memo中。

这是Header的样子:

class Header extends React.Component {
  shouldComponentUpdate() {
    return false
  }

  render() {
    const { title, description } = this.props
    return (
      <header role="banner">
        <h1>{title}</h1>
        <h2>{description}
      </header>
    )
  }
}

感谢阅读。

我有一个Gatsby网站,它在Layout.js中返回以下模式

{props.children}
在我的所有页面文件中,例如index.js和Blog。 js ...
javascript reactjs gatsby
1个回答
0
投票

您应该在Layout.js中使用方法shouldComponentUpdate,您也可以阅读文章https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/using_should_component_update.html

© www.soinside.com 2019 - 2024. All rights reserved.