如何将 React.memo 与包含子项的组件一起使用 [英] how to use React.memo with a Component contains children
本文介绍了如何将 React.memo 与包含子项的组件一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
需要帮助~
我有两个组件,我用 React.memo 包裹了 Parent:
孩子
const Child = ()=><div>我是孩子</div导出默认子项
家长
const Parent = (props)=><div>{props.children}</div>导出默认 React.memo(Parent)
在应用中使用:
const App = () =>{const [count, setCount] = useState(0)返回(<div><button onClick={()=>setCount(count+1)}></button><家长><孩子></孩子></父母>
)}
点击按钮,结果:
父组件将重新渲染,所以备忘录不起作用,因为它的子组件是一个函数组件
那么,如何防止重新渲染?
我知道用useMemo解决的方法,但是又丑又不友好,大家有更好的想法吗?
const App = () =>{const [count, setCount] = useState(0)const children = useMemo(()=> ,[])返回(<div><button onClick={()=>setCount(count+1)}></button><家长>{孩子们}</父母>
)}
解决方案
用 React.memo
包裹你的
:
const Child = ()=>{console.log('render')//只触发一次 - 在初始渲染时return <div>我是孩子</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);返回(<div><button onClick={()=>setCount(count+1)}>增加{count}</button><MParent><MChild></MChild></MParent>
)}render(<App/>, document.getElementById('root'));
need some help ~
I have two Components, and I wrapped Parent with React.memo:
Child
const Child = ()=> <div>I'm Child</div
export default Child
Parent
const Parent = (props)=> <div>{props.children}</div>
export default React.memo(Parent)
Use in App:
const App = () => {
const [count, setCount] = useState(0)
return(
<div>
<button onClick={()=>setCount(count+1)}></button>
<Parent>
<Child></Child>
</Parent>
</div>
)
}
Click the button, result:
The Parent Component will rerender, so the memo not working because it's children is a function component
So, how can I prevent rerender?
I know a way to solve by useMemo, but it's ugly and not friendly, do you have better ideas?
const App = () => {
const [count, setCount] = useState(0)
const children = useMemo(()=><Child></Child>,[])
return(
<div>
<button onClick={()=>setCount(count+1)}></button>
<Parent>
{children}
</Parent>
</div>
)
}
解决方案
Wrap your <Child />
with 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'));
这篇关于如何将 React.memo 与包含子项的组件一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!