簡體   English   中英

基於狀態/屬性值的可控制渲染的React Hooks功能組件

[英]React Hooks function component with controlled rendering based on state/prop values

能夠在React Class組件上使用shouldComponentUpdate的好處之一是能夠基於條件而不是僅更改狀態/ prop值來控制渲染。

使用功能組件中的react鈎子進行此優化的首選方法是什么?

在下面的示例中,即使類組件處於(或保持)關閉狀態,它也不會重新呈現,即使它具有新的子代也是如此。

class DrawerComponent extends React.Component {
  static propTypes = {
    children: PropTypes.any,
  }

  state = {
    isOpen: false,
  }

  // only re-render if the drawer is open or is about to be open.
  shouldComponentUpdate(nextProps, nextState) {
    return this.state.isOpen || nextState.isOpen;
  }

  toggleDrawer = () => {
    this.setState({isOpen: !this.state.isOpen});
  };

  render() {
    return (
      <>           
        <div onClick={this.toggleDrawer}>
          Drawer Title
        </div>
        <div>
          {this.state.isOpen ? this.props.children : null}
        </div>
      </>
    )
  }
}

功能組件對應項(無優化):

function DrawerComponent({ children }) {
  const [isOpen, setIsOpen] = useState(false);

  function toggle() {
    setIsOpen(!isOpen);
  } 

  return (
    <>
      <div onClick={toggle}>
        Drawer Title
      </div>
      <div>{isOpen ? children : null}</div>
    </>
  );
}

在本例中,我認為不需要對shouldComponentUpdate優化。 由於您在關閉抽屜時不渲染children ,因此它已經非常快了。 運行功能組件的成本幾乎可以忽略不計。

就是說,如果您確實想在功能組件中實現等效行為,則可以使用React.memo並提供自定義的areEqual函數: https : areEqual

暫無
暫無

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

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