Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

javascript - 防止组件进入 <Layout /> 从重新渲染(Prevent a component in <Layout /> from re-rendering)

I have a Gatsby site which returns following pattern in Layout.js

(我有一个Gatsby网站,该网站在Layout.js返回以下模式)

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

In all of my page files such as index.js and blog.js I've wrapped the content in the Layout component so the header and footer appears on both.

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

<Layout>
  Some content here
</Layout>

The problem I'm having is that the Header component re-renders on each route change, which I'd like to prevent as it's very obvious when it happens due to an animation.

(我遇到的问题是Header组件会在每次更改路线时重新渲染,这是我想防止的,因为当它由于动画而发生时非常明显。)

Is there a secondary layer to Gatsby that I can place the Header and Footer component so they are outside of the Layout which gets re-rendered with the new page content?

(Gatsby是否有第二层,我可以放置HeaderFooter组件,使它们位于Layout之外,而Layout用新的页面内容重新呈现?)

I've tried wrapping them around the root element in html.js but this causes a FOUT issue.

(我尝试将它们包装在html.jsroot元素周围,但这会导致FOUT问题。)

I've tried using this official plugin: https://www.gatsbyjs.org/packages/gatsby-plugin-layout/ and updated my index.js and blog.js accordingly to remove the wrapping Layout component.

(我尝试使用此官方插件: https : blog.js ,并相应地更新了index.jsblog.js ,以删除包装的Layout组件。)

The problem I have with this is that route changes no longer cause Layout to re-render at all, so the content doesn't update.

(我的问题是,路线更改根本不再导致Layout重新渲染,因此内容不会更新。)

I've also tried returning false in shouldComponentUpdate , and tried wrapping the Header component in memo .

(我还尝试过在shouldComponentUpdate返回false ,并尝试将Header组件包装在memo 。)

Here's what Header looks like.

(这是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>
    )
  }
}

Thanks for reading.

(谢谢阅读。)

  ask by James Ives translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...