我有一个React组件Activity,带有一个DataTable和一个Drawer(来自Material UI)。我根据Activity组件的状态isDrawerOpen
属性设置是否打开抽屉。但是,更新isDrawerOpen
时,Activity,Drawer和DataTable都将重新呈现。
我不希望DataTable
重新提交,因为没有任何变化。我尝试使用React.memo
,并尝试在DataTable功能组件中将useEffect
与useRef
结合使用,以在道具相同时不重新呈现。没用当其所有道具都没有变化时,如何防止该子组件重新呈现?
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>
)
}
答案 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>
);
}