直播于codesandbox
我有一个简单的例子
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
组件。
答案 0 :(得分:1)
为了防止重新渲染,您可以记住组件。
export default function App() {
const [items,setItems]=useState([]);
const memoizedShouldNotRender = useMemo(() => <ShouldNotRender/>, []);
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>
{memoizedShouldNotRender}
</div>
);
}
查看文档:{{3}}
答案 1 :(得分:1)
您也可以使用 React.memo()
"message": "Item not found",