yığınlama nedir
Toplu işleme, yeniden oluşturmayı birleştirmektir.
React17 veya önceki sürümlerde, aşağıdaki kod yeniden oluşturmayı yalnızca bir kez tetikleyecektir.
function App() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
function handleClick() {
setCount(c => c + 1); // Does not re-render yet
setFlag(f => !f); // Does not re-render yet
// React will only re-render once at the end (that's batching!)
}
return (
<div>
<button onClick={handleClick}>Next</button>
<h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>
</div>
);
}Ancak aşağıdaki kodda iki kez tetiklenecektir: onClick sentetik olayının geri çağrısı toplu işlemi başlatacak olsa da, setCount ve setFlag bu geri çağrıdan sonra yürütülür (toplama sırasında değil), bu nedenle yeniden oluşturma iki kez tetiklenir.function App() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
function handleClick() {
fetchSomething().then(() => {
setCount(c => c + 1); // Causes a re-render
setFlag(f => !f); // Causes a re-render
});
}
return (
<div>
<button onClick={handleClick}>Next</button>
<h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>
</div>
);
}Otomatik yığınlama nedir
Kök bileşeniniz aracılığıyla işleniyorsa ReactDOM.createRoot(...).render(...), aşağıdaki kodda, durumda yapılan iki değişiklik bir söz, setTimeout veya yerel olayda olsalar bile yalnızca bir yeniden oluşturmayı tetikler.
function App() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
function handleClick() {
fetchSomething().then(() => {
// React 18 and later DOES batch these:
setCount(c => c + 1);
setFlag(f => !f);
// React will only re-render once at the end (that's batching!)
});
}
return (
<div>
<button onClick={handleClick}>Next</button>
<h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>
</div>
);
}React18'de Otomatik gruplama nasıl kapatılır
- Seçenek 1: ReactDOM.render(<App />, rootElement);: Yalnızca createRoottoplu güncelleme etkinleştirilebilir
- Seçenek 2: tepki-dom kullanmaflushSync
import { flushSync } from 'react-dom'; // Note: react-dom, not react
function handleClick() {
flushSync(() => {
setCounter(c => c + 1);
});
// React has updated the DOM by now
flushSync(() => {
setFlag(f => !f);
});
// React has updated the DOM by now
}
