当父状态在React中发生变化时,停止渲染子组件

时间:2020-04-10 16:11:24

标签: reactjs

我有一个React组件Activity,带有一个DataTable和一个Drawer(来自Material UI)。我根据Activity组件的状态isDrawerOpen属性设置是否打开抽屉。但是,更新isDrawerOpen时,Activity,Drawer和DataTable都将重新呈现。

我不希望DataTable重新提交,因为没有任何变化。我尝试使用React.memo,并尝试在DataTable功能组件中将useEffectuseRef结合使用,以在道具相同时不重新呈现。没用当其所有道具都没有变化时,如何防止该子组件重新呈现?

const Activity = props => {
   const [isDrawerOpen, setIsDrawerOpen] = useState(false);
   const [tableData, setTableData] = useState(["banana", "orange", "apple"]);

   return (
      <div>
        <DataTable data={tableData} onRowClick={() => setIsDrawerOpen(true) } />
        <Drawer open={isDrawerOpen}>Some Drawer Content </Drawer>
      </div>
   )
}

1 个答案:

答案 0 :(得分:3)

尽管情况实际上正在发生变化……它正在onRowClick的每个渲染器上构造一个新函数,然后由于其获得了新的道具而迫使孩子重新渲染。这是useCallback钩子的作用:

const Activity = props => {
   const [isDrawerOpen, setIsDrawerOpen] = useState(false);
   const [tableData, setTableData] = useState(["banana", "orange", "apple"]);

   // Because `setIsDrawerOpen` never changes across renders, it's safe to
   // pass an empty deps array as the second argument.
   const onRowClick = useCallback(() => setIsDrawerOpen(true), []);

   return (
      <div>
        <DataTable data={tableData} onRowClick={onRowClick} />
        <Drawer open={isDrawerOpen}>Some Drawer Content </Drawer>
      </div>
   );
}