嵌套组件如何渲染?

How a Nested Component become render?

让我们创建一个在包含嵌套组件的页面中使用的组件。 例如 -

containerComponent.tsx

import NestedComponent from '../components/nestedComponent';

const ContainerComponent = () => {
  const { value, setValue} = useState(0);

  return (
      <>
        <h1>This is the Nested Component</h1>
        <NestedComponent />
        <button onClick={()=>setValue(value+1)}>
          {{ value }} time Updated
        </button>
      </>
  );
};

export default ContainerComponent;

这里我们使用了index.tsx中的父组件如下-

index.tsx

import ContainerComponent from '../components/containerComponent';

const Home = ()=> {
  return (
      <div>
        <ContainerComponent />
      </div>
  );
};

export default Home;

Here when i click on the button from the view of home page the "value" state variable is updated & the ContainerComponent (parent of NestedComponent) become re-render. But is the nested component also render ? (Though there is no parameter or props value passed through nested component from it's parent.)

您好,使用 React.memo 导出您的 NestedComponent,那么当 ContainerComponent 中的任何状态发生更改时,它都不会被渲染。这是针对功能组件的。

这是代码

import React, {useState} from "react";

const NestedComponent = () => {
    const {value, setValue, errors} = useState(0);
    console.log('child');
    return (
        <div>
            ContainerComponent
        </div>
    );
};

export default React.memo(NestedComponent);

对于 class 组件, 你应该从 React.PureComponent 扩展你的 class 而不是 React.Component 像..

class NestedComponent extends React.PureComponent{
   render(){
      ...
   }
}