-
子衿沉夜
import React, { useState } from "react";import "./styles.css";export default function App() { const [counter, setCounter] = useState(0); const [asyncCounter, setAsyncCounter] = useState(0); return ( <div className="App"> <div> <button onClick={async () => { //sets the asyncCounter state to the counter states after a 4 seconds timeout let tempCounter = counter; await new Promise(resolve => { setTimeout(() => { resolve(); }, 4000); }); if (tempCounter !== counter) { alert("counter was changed"); } else { setAsyncCounter(counter); } }} > Async </button> <label>{asyncCounter}</label> </div> <div> <button onClick={() => { //increases the counter state setCounter(counter + 1); }} > Add 1 </button> <label>{counter}</label> </div> </div> );}<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
-
FFIVE
您可以使用 ref 独立跟踪计数器值 const [counter, setCounter] = useState(0); const counterRef = useRef(counter)每当您更新 counter 时,您也会更新 counterRef:const newCounter = counter + 1setCounter(newCounter);counterRef.current = newCounter然后检查它:if (counterRef.current !== counter) { alert("counter was changed");} else { setAsyncCounter(counter);}Codesandox
-
倚天杖
正如@thedude 所提到的,您将需要使用useRef钩子——它是为您的用例而制作的,正如文档所说:“它可以方便地保留任何可变值,类似于您在类中使用实例字段的方式。”我想你可能只想添加一个简单的 boolean: const counterChanged = useRef(false);然后当你更新计数器时,你也会更新它。 counterChanged.current = true; setCounter(counter + 1);在您的 async 函数中,将其设置为 false ,然后检查它是否已更改。counterChanged.current = false; await new Promise(resolve => { setTimeout(() => { resolve(); }, 4000); }); if (counterChanged.current) { // alert
-
蝴蝶刀刀
通过在 facebook-rect github 上提问,我找到了另一个答案。显然,由于设置状态是一个函数,它的第一个参数是当前状态。因此可以在设置计数器值时使用此代码段访问先前的值: setCounter(prevValue => { alert(prevValue + " " + counter); return counter + 1; });https://github.com/facebook/react/issues/19270 https://reactjs.org/docs/hooks-reference.html#functional-updates