问题是:我试图在单击按钮时调用 2 个函数。这两个函数都会更新状态(我正在使用 useState 钩子)。第一个函数将 value1 正确更新为“new 1”,但在 1s (setTimeout) 后第二个函数触发,并将值 2 更改为“new 2”但是!它将 value1 设置回“1”。为什么会这样?提前致谢!
import React, { useState } from "react";
const Test = () => {
const [state, setState] = useState({
value1: "1",
value2: "2"
});
const changeValue1 = () => {
setState({ ...state, value1: "new 1" });
};
const changeValue2 = () => {
setState({ ...state, value2: "new 2" });
};
return (
<>
<button
onClick={() => {
changeValue1();
setTimeout(changeValue2, 1000);
}}
>
CHANGE BOTH
</button>
<h1>{state.value1}</h1>
<h1>{state.value2}</h1>
</>
);
};
export default Test;