我的父组件有多个子组件,我只想重新渲染选定的子组件,而不是一遍又一遍地重新渲染父组件。
const ParentComp = () =>
{
const [state1, setState1] = useState(0);
const [state2, setState2] = useState(0);
const [state3, setState3] = useState(0);
// ... more children if needed
// example: do something complex based on events
// and update states for desired component
return(
// ... parent stuff
<ChildComp1 state=state1/>
<ChildComp1 state=state2/>
<ChildComp1 state=state3/>
// ... parent stuff
)
}
我可以将子组件包裹在备忘录中,它将渲染选定的子组件,但仍会重新渲染父组件。
这样的事情怎么样:
import React, { useState, useCallback, memo } from 'react';
const ChildComp1 = memo(({ state }) => {
console.log("ChildComp1 state:", state);
return <div>{state}</div>;
});