需要一些帮助〜
孩子
const Child = ()=> <div>I'm Child</div
export default Child
父母
const Parent = (props)=> <div>{props.children}</div>
export default React.memo(Parent)
const App = () => {
const [count, setCount] = useState(0)
return(
<div>
<button onClick={()=>setCount(count+1)}></button>
<Parent>
<Child></Child>
</Parent>
</div>
)
}
父组件将重新呈现,因此备忘录不起作用,因为它的子组件是功能组件
我知道用useMemo解决的方法,但是它很丑陋而且不友好,您有更好的主意吗?
const App = () => {
const [count, setCount] = useState(0)
const children = useMemo(()=><Child></Child>,[])
return(
<div>
<button onClick={()=>setCount(count+1)}></button>
<Parent>
{children}
</Parent>
</div>
)
}
答案 0 :(得分:1)
用<Child />
将React.memo
包裹起来:
const Child = ()=> {
console.log('render') // fires only once - on initial render
return <div>I'm Child</div>
}
const MChild = React.memo(Child);
const Parent = (props)=> <div>{props.children}</div>
const MParent = React.memo(Parent)
const App = () => {
const [count, setCount] = useState(0);
return(
<div>
<button onClick={()=>setCount(count+1)}>increment {count}</button>
<MParent>
<MChild></MChild>
</MParent>
</div>
)
}
render(<App />, document.getElementById('root'));
答案 1 :(得分:1)
const children = useMemo(()=><Child></Child>,[])
是最简单的方法。使用memo(Child)
无效,因为jsx实际上在您每次调用<Child />
时都会返回一个新对象。 React.memo
默认情况下仅使用简单的浅表比较,因此实际上没有其他直接方法可以解决它。您可以创建自己的函数,该函数最终将支持子级并将其传递给React.memo(MyComp, myChildrenAwareEqual)
。
答案 2 :(得分:0)
将 <Parent><Child/></Parent>
移动到一个单独的组件中,并记住 那个 组件:
const Family = memo(() => <Parent><Child/></Parent>);
const App = () => {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count => count + 1)}>{count}</button>
<Family />
</>
)
}