setState函数(功能组件)不会在控制台中更新状态

时间:2020-03-31 07:21:31

标签: reactjs

我有一个功能组件,可以说变量是:

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也会显示错误的值。

如果复选框为true,则显示为false。 如果该复选框为false,则显示为true。

该功能当前似乎尚未更新状态,但可以在复选框本身上正常工作。

更平淡的输出:

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

是:

当复选框为true时:

true
false

以及为假时的情况:

false
true

1 个答案:

答案 0 :(得分:0)

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

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

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

希望这会有所帮助!

相关问题