我有一个简单的例子
import "./styles.css";
import {useState} from "react";
const Child=({text,idx})=>{
console.log(`Child - ${idx} rendered`);
return <li>{text}</li>
}
const ShouldNotRender=()=>{
console.log("Should not render")
return <p>Should not render</p>
}
export default function App() {
const [items,setItems]=useState([]);
return (
<div className="App">
<button onClick={(e)=>{
setItems([...items,parseInt(Math.random()*500,10)]);
}}>Add list</button>
<ul>
{items.map((item,idx)=>{
return <Child text={item} key={idx} idx={idx}/>
})}
</ul>
<ShouldNotRender/>
</div>
);
}
您可以看到,每当我们将一个项目添加到列表中时,ShouldNotRender
它也会重新呈现。ShouldNotRender
不依赖于任何状态,则不应重新渲染。它是一个静态且沉重的组件(canvas)
。
我想将组件分为两个其他组件,一个是静态的,另一个是动态的。好吧,它工作正常,但是我不明白为什么要反应ShouldNotRender
组件。
您也可以使用 React.memo()
const ShouldNotRender = React.memo(() => {
console.log("Should not render");
return <p>Should not render</p>;
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句