Settimeout工作不正常,正在获取第一个值



我正在尝试使用setinterval来更改secondCall的值。但在2秒后,加载的值可能会变为false,但settimeout会取第一个true值。如何使settimeout取加载的更新值?

export const sleep = async (callback = null, timeInMs = 3000) =>
new Promise((resolve) => setTimeout(() => resolve(callback), timeInMs));
useEffect(() => {
async function delay() {
await sleep(30000);
if (loading) {
setSecondCall(true);
}
}
delay();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

就像30秒后,如果加载等于false,就不应该在secondCall上进行更改。

delay函数中的loading是闭包捕获的,它不会随着时间的推移而改变,但您可以使用useRef实现您想要的。

export default function App() {
const loadingRef = useRef(true); // same as loading
const [loading, setLoading] = useState(true);
const [secondCall, setSecondCall] = useState(false);
// hook to update loadingRef only
useEffect(() => {
loadingRef.current = loading;
}, [loading]);
useEffect(() => {
async function delay() {
// btw, in your sleep the delay is 2nd parameter
await sleep(null, 30000);
// loadingRef is closure-captured
// but .current is not and will be reflected as expected
if (loadingRef.current === true) {
setSecondCall(true);
}
}
delay();
}, []);
return <div className="App">...</div>;
}

最新更新