4 回答

TA貢獻1828條經驗 獲得超3個贊
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>

TA貢獻1797條經驗 獲得超6個贊
您可以使用 ref 獨立跟蹤計數器值
const [counter, setCounter] = useState(0);
const counterRef = useRef(counter)
每當您更新 counter 時,您也會更新 counterRef:
const newCounter = counter + 1
setCounter(newCounter);
counterRef.current = newCounter
然后檢查它:
if (counterRef.current !== counter) {
alert("counter was changed");
} else {
setAsyncCounter(counter);
}
Codesandox

TA貢獻1828條經驗 獲得超3個贊
正如@thedude 所提到的,您將需要使用useRef鉤子——它是為您的用例而制作的,正如文檔所說:“它可以方便地保留任何可變值,類似于您在類中使用實例字段的方式?!?/p>
我想你可能只想添加一個簡單的 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

TA貢獻1801條經驗 獲得超8個贊
通過在 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
添加回答
舉報