Re-渲染
一句话解释
re-渲染 occurs 当组件's 状态 or Props 更改, or 当 parent re-渲染 — causing 组件函数到 运行再次.
用大白话说
A component re-renders (its function runs again) when: (1) its own state changes (via a setState call), (2) its props change (because the parent re-rendered and passed new props), or (3) its parent re-renders (by default, children re-render when the parent does).
这个third case is the most common source of unnecessary re-renders. If a parent changes state that only it cares about, all children still re-render even if their props are identical. React.memo prevents this by skipping the re-render when props are unchanged.
To minimize re-renders: keep state close to where it's used, split components so only the parts that need to update do, use React.memo for expensive children, and avoid passing new object/array/function references as props on every render.
示例
function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(c => c + 1)}>Inc</button>
<Child /> {/* Re-renders every time count changes, even though
Child has no props and doesn't use count */}
</div>
);
}每个点击更改数量, causing Parent 到 re-渲染, 哪个 causes Child 到 re-渲染即使 Child's Props haven't 更改.
相关术语
相关资源
相关课程
- 性能 Optimization
学习到 reduce 不必要 re-渲染.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。