Open nmsn opened 2 years ago
在 React 18之前,我们只在反应事件处理过程中批量更新。在 React 默认情况下,promises、 setTimeout、本机事件处理程序或任何其他事件中的更新都不会批处理。
从 18 开始,所有的更新都会自动批处理,不管它们来自哪里。
无论更新发生在哪里,React 都会自动批量更新,因此:
function handleClick() {
setCount(c => c + 1);
setFlag(f => !f);
// React will only re-render once at the end (that's batching!)
}
setTimeout(() => {
setCount(c => c + 1);
setFlag(f => !f);
// React will only re-render once at the end (that's batching!)
}, 1000);
behaves the same as this:
fetch(/*...*/).then(() => {
setCount(c => c + 1);
setFlag(f => !f);
// React will only re-render once at the end (that's batching!)
})
elm.addEventListener('click', () => {
setCount(c => c + 1);
setFlag(f => !f);
// React will only re-render once at the end (that's batching!)
});
有相同的表现形式。
https://github.com/reactwg/react-18/discussions/21