簡體   English   中英

React:如何使用map()渲染多個菜單而又不導致重新渲染?

[英]React: How can I render multiple menus with map() without causing a re-render?

我有一個名為<SiteMenu />的組件。 在我的渲染函數中,我有以下三行:

render() {
    { this.renderPrimaryMenu() }
    { secondaryMenuContents && this.renderSecondaryMenu() }
    { this.renderAdditional() }
}

每個菜單項都有一個對應的功能,可以映射結果並創建菜單作為無序列表。 簡化版本:

renderAdditional() {
    const { secondaryMenuContents } = this.props;
    if (!secondaryMenuContents) { return false; }

    const additional = filter(secondaryMenuContents.sections, { additional: true });
    if (!additional || additional.length === 0) { return false; }

    const links = additional.map(
        (link, index) => {
            return (
                <Link
                    key={ `${index}-${link.link}` }
                    to: link.link
                >
                    { link.text }
                </Link>
            );
        }
    );

    return (
        <nav className={ styles['nav--additional'] }>
            <Responsive>
                <h3 className={ styles.h3 }>{ Lang.additionalSection.title }</h3>
                <menu className={ styles['menu--additional'] }>
                    { links }
                </menu>
            </Responsive>
        </nav>
    );
}

每次呈現這些列表之一時,它都會重新呈現整個組件。 其中一個菜單使用靜態JSON( renderPrimaryMenu() ),而另兩個菜單則依賴於API兩次單獨調用中的數據,因此數據不一定總是同時輸入。

確保單個渲染的任何建議,或者更好的是,顯示第一個靜態菜單(隨每個渲染淡入並重新淡入),並在准備就緒時顯示另外兩個渲染而不會導致第一個菜單重新渲染?

感謝我可以獲得的任何幫助!

我建議您將這三個部分分開。

並使用shouldComponentUpdate()來確保是否重新渲染組件。

這是偽代碼:

class PrimaryMenu extends Component {
  shouldComponentUpdate() {
    // if data is the same, return false
    // else return true
  }

  render() {
    return (
      ...
    )
  }
}

class SecondaryContent extends Component {
  // same logic as PrimaryMenu
}

class Additional extends Component {
  // same logic as PrimaryMenu
}

class SiteMenu extends Component {
  render() {
    return (
      <PrimaryMenu/>
      <SecondaryContent/>
      <Additional/>
    )
  }
}

因此,使用此設置,您可以在每個Menu控制重新渲染時間。

或嘗試使用PureComponent,它可以減少重新渲染的內容。

import React, { PureComponent } from 'react';

class Additional extends PureComponent {

}

更多信息https://reactjs.org/docs/react-api.html#reactpurecomponent

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM