如何在同一函数中更改useState变量

我有这个变量

const [userName, setUserName] = useState<string>("initialValue");

并单击按钮,我执行此功能

const FacebookSign = () => {
    console.log(userName);
    setUserName("value2");
    console.log(userName);
}

userName变量没有改变,我的输出是

initialValue
initialValue

但是如果第二次点击按钮,我得到了输出

value2
value2

为什么值第一次不改变?

评论
胖子
胖子

If you read about how the state change mechanism works. The process is asynchronous in nature. So may or may not change immediately. Read more about it here Is useState synchronous?

点赞
评论