【问题标题】:setState function (functional components) don't update state in consolesetState 函数(功能组件)不会在控制台中更新状态
【发布时间】:2020-07-11 16:36:17
【问题描述】:

我有一个函数组件,假设变量是:

const [currentValue, setCurrentValue] = useState(false);

我有一个这样的复选框:

<label for='checking'><input type="checkbox" id="checking" checked={currentValue ? true : false} onChange={e => handleChecking(e)} />

然后我有一个函数:

const handleChecking = (e) => {
    setCurrentValue(e.target.checked);
    console.log(currentValue);
}

现在的问题是,即使复选框按预期运行,console.log 显示的值也不正确。

当复选框为真时,它显示我为假。 当复选框为假时,它显示为真。

目前在函数中似乎没有更新状态,但在复选框本身上按预期工作。

为了更直白,输出如下:

    console.log(e.target.checked);
    setCurrentValue(e.target.checked);
    console.log(currentValue);

是:

当复选框为真时:

true
false

当它为假时:

false
true

【问题讨论】:

  • 为什么你检查的属性不是checked={currentValue}
  • 我只是简化了这个例子,是的,我们可以在这个例子中使用checked={currentValue},但我仍然面临这个问题。

标签: reactjs


【解决方案1】:

useState 钩子是异步的,不会立即反映更新的值。

您可以使用useEffect 访问更改后的值。

useEffect(() => {
  console.log(currentValue);
}, [currentValue])

希望这会有所帮助!

【讨论】:

  • 我什至尝试了 setTimeout,但也没有获取正确的值。
  • 你也可以把这个console.log(currentValue);就在组件的 jsx return 语句之前,还设置 timeOut 并不能保证
  • 如果我想根据changedValue做一些其他的事情怎么办?我可以从useEffect() 内部调用该函数吗?所以我在handleChecked() 中设置了CurrentValue(),然后我想执行一些额外的任务。我应该将所有这些任务移到useEffect() 中吗?
猜你喜欢
  • 2022-07-27
  • 2022-01-21
  • 2021-08-24
  • 1970-01-01
  • 2021-10-15
  • 2022-11-22
  • 2018-08-05
相关资源
最近更新 更多