Почему задержка в одно надатие?
Учу Cheakbox и разбираю код с помощью откладки, и увидела непонятную для меня штуку, что в переменную allchecked
не сразу добавляется/удаляется значения cheakbox, те чтобы в массив занеслась переменная с cheakbox, нужно удалить/добавить другой cheakbox, грубо говоря массив обновляется, через одно действие, а не сразу. Почему так?
Код:
//import React from "react";
const App = () => {
const [allchecked, setAllChecked] = React.useState([]);
function handleChange(e) {
if (e.target.checked) {
setAllChecked([...allchecked, e.target.value]); //Вот здесь массив не сразу обновляется почему?
} else {
setAllChecked(allchecked.filter((item) => item !== e.target.value));
}
}
return (
<div>
<h4>
{" "}
Creating the {" "}
<i>
{" "}
Custom controlled checkbox and handling the multiple checkboxes
{" "}
</i>{" "} in the React application {" "}
</h4>
<div>
<input value = "One" type = "checkbox" onChange = {handleChange} />
<span> One </span>
</div>
<div>
<input value = "Two" type = "checkbox" onChange = {handleChange} />
<span> Two </span>
</div>
<div>
<input value = "Three" type = "checkbox" onChange = {handleChange} />
<span> Three </span>
</div>
<div>
<input value = "Four" type = "checkbox" onChange = {handleChange} />
<span> Four </span>
</div>
<div>
<input value = "Five" type = "checkbox" onChange = {handleChange} />
<span> Five </span>
</div>
<div>The all checked values are {allchecked.join(" , ")}</div>
</div>
);
};
// export default App;
const domContainer = document.querySelector('#like_button_container');
const root = ReactDOM.createRoot(domContainer);
root.render(<App />);
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<div id="like_button_container"></div>
Источник: Stack Overflow на русском