因此,我想做的是将事件侦听器添加到按钮,按下该按钮时将获取状态值并控制台记录它。但即使在多次 setState 调用之后,记录的值也永远不会更新。
useEffect(() => {
const seamCarve = document.getElementById("process");
seamCarve.addEventListener("click", (e) => {
console.log(seamValue);
});
}, []);
Run Code Online (Sandbox Code Playgroud)
然后就是触发它的按钮
<div id="seamvalue">
<Typography variant="h6" align="center">
Seams Reduction:<span id="valueOfSeam"> {seamValue} </span>
</Typography>
</div>
<Button
id="leftslider"
variant="contained"
color="primary"
onClick={() =>
seamValue - 10 > 0 ? setSeamValue(seamValue - 10) : setSeamValue(0)
}
>
<Typography>{"<"}</Typography>
</Button>
<Button
id="rightslider"
variant="contained"
color="primary"
onClick={() => setSeamValue(seamValue + 10)}
>
<Typography>{">"}</Typography>
</Button>
<Button id="process" variant="contained" color="primary">
<Typography>Carve</Typography>
</Button>
Run Code Online (Sandbox Code Playgroud)
当我单击滑块时,该值会发生变化,但是当我按下 id="process" 的按钮以及与其关联的事件侦听器时,即使在更新状态后,它也只会打印 20。