今天以场景来举例子
import { useState, useEffect } from "react";
import { Button, message } from "antd";
const Index = () => {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setTimeout(() => {
setCount((v) => v + 1);
}, 2000);
return () => {
clearTimeout(timer);
};
}, []);
useEffect(() => {
const timer = setTimeout(() => {
message.info(`当前的count为:${count}`);
}, 3000);
return () => {
clearTimeout(timer);
};
}, []);
return (
<div style={{ padding: 20 }}>
<div>数字:{count}</div>
<Button onClick={() => setCount((v) => v + 1)}>加1</Button>
</div>
);
};
export default Index;
一种场景下 我先去定时,两秒会设置值,同时在期间点击两次加
- count --- 加了两次,同时每次都是在原有的基础上进行添加,所以是二
- 此时再去定时加1 所以
- 最终视图渲染一定是3
- 但是由于setSTate 是异步的所以访问依然是引用了当前上下文下的最初始值,除非多次执行。
原理待补充