简体   繁体   English

基于状态/属性值的可控制渲染的React Hooks功能组件

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

One of the benefits of being able to use shouldComponentUpdate on a React Class component is the ability to control the render based on a condition rather than just a change in state/prop values. 能够在React Class组件上使用shouldComponentUpdate的好处之一是能够基于条件而不是仅更改状态/ prop值来控制渲染。

What is the preferred way to make this optimization using react hooks in a function component? 使用功能组件中的react钩子进行此优化的首选方法是什么?

In the example below, the class component does not re-render if it is (or is staying) in a closed state, even if it has new children. 在下面的示例中,即使类组件处于(或保持)关闭状态,它也不会重新呈现,即使它具有新的子代也是如此。

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 component counterpart (without optimization): 功能组件对应项(无优化):

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

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

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

In this example, in my opinion there's no need for a shouldComponentUpdate optimization. 在本例中,我认为不需要对shouldComponentUpdate优化。 It will already be fast since you're not rendering the children when the drawer is closed. 由于您在关闭抽屉时不渲染children ,因此它已经非常快了。 The cost of running the functional component will be fairly negligible. 运行功能组件的成本几乎可以忽略不计。

That said, if you did want to implement the equivalent behavior in a functional component, you could use React.memo and supply a custom areEqual function: https://reactjs.org/docs/react-api.html#reactmemo . 就是说,如果您确实想在功能组件中实现等效行为,则可以使用React.memo并提供自定义的areEqual函数: https : areEqual

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM