[英]In React, does a list of memo component get rendered if they are inside the map function called from the a list state?
Assuming I have a memoized child component:假设我有一个备忘的子组件:
function Child({number}){
return <div> {number} </div>;
}
export React.memo(child)
The Child component only gets rerender if the number props is changed.如果更改了 number 属性,则 Child 组件只会重新渲染。
Now, I put the Child component inside the Parent component.现在,我将 Child 组件放在 Parent 组件中。 The parent component is as of following:
父组件如下:
function Parents(){
const [numbers, setNumbers] = useState([1,2,3,4,5,6]);
return (
<>
numbers.map((number,index)=>{
<Child key={index} number={number}>
}
</>
)
}
So, in this case, the Child components are generated inside a loop over the numbers array.因此,在这种情况下,子组件是在数字数组的循环内生成的。 However, the child components are memoized.
但是,子组件会被记忆。 In case when only one number is changed in the array, for example, if we change
[1,2,3,4,5,6]
to [ 1,2,111111,4,5,6]
.如果数组中只有一个数字发生变化,例如,如果我们将
[1,2,3,4,5,6]
更改为 [ 1,2,111111,4,5,6]
。 The third number goes from 3 to 111111. Now, does the every child element get rerendered, or only the third child elements get rerender?第三个数字从 3 到 111111。现在,是每个子元素都被重新渲染,还是只有第三个子元素被重新渲染?
In this case, only the third child will be re-rendered , as the props for the other children will be the same在这种情况下,只有第三个孩子会被重新渲染,因为其他孩子的道具是一样的
You can check this for yourself using the following example:您可以使用以下示例自行检查:
import {memo, useState} from 'react'
const Child = memo(({number}) => {
console.log('re-render', number);
return <div>{number}</div>;
})
export default function App() {
const [numbers, setNumbers] = useState([1,2,3,4,5,6]);
return (
<>
{numbers.map((number,index)=>
<Child number={number} /> )
}
<button onClick={() => {
setNumbers(prev => {
prev[2] = 111;
return [...prev];
})
}}>
click
</button>
</>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.