子组件在每次状态更改时重新渲染
Child component rerendered on every state changes
生活在 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
组件。
为了防止重新渲染,您可以记忆组件。
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>
);
}
您也可以使用React.memo()
const ShouldNotRender = React.memo(() => {
console.log("Should not render");
return <p>Should not render</p>;
});
生活在 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
组件。
为了防止重新渲染,您可以记忆组件。
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>
);
}
您也可以使用React.memo()
const ShouldNotRender = React.memo(() => {
console.log("Should not render");
return <p>Should not render</p>;
});