useState是同步的吗? [英] Is useState synchronous?

查看:2022
本文介绍了useState是同步的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去,我们已经明确警告过,调用setState({myProperty})是异步的,并且this.state.myProperty的值在回调或下一个render()方法之前是无效的.

In the past, we've been explicitly warned that calling setState({myProperty}) is asynchronous, and the value of this.state.myProperty is not valid until the callback, or until the next render() method.

使用useState,如何在显式更新状态后获取状态的值?

这对钩子如何起作用?据我所知,useState的setter函数不会接受回调,例如

How does this work with hooks? As far as I can tell, the setter function of useState doesn't take a callback, e.g.

const [value, setValue] = useState(0);
setValue(42, () => console.log('hi callback');

不会导致回调运行.

在旧世界中,我的另一种解决方法是将实例变量(e.g. this.otherProperty = 42)挂在类上,但这在这里不起作用,因为没有可重用的函数实例(严格模式下没有this). /p>

My other workaround in the old world is to hang an instance variable (e.g. this.otherProperty = 42) on the class, but that doesn't work here, as there is no function instance to reuse (no this in strict mode).

推荐答案

您可以使用 useEffect 在更新后访问最新状态.如果您有多个状态挂钩,并且只想跟踪其中的一部分更新,则可以将状态作为useEffect函数的第二个参数传递给数组:

You can use useEffect to access the latest state after updating it. If you have multiple state hooks and would like to track the update on only part of them, you can pass in the state in an array as the second argument of the useEffect function:

useEffect(() => { console.log(state1, state2)}, [state1])

仅当更新state1时才会调用上述useEffect,并且您不应信任此函数内部的state2值,因为它可能不是最新的.

The above useEffect will only be called when state1 is updated and you shouldn't trust the state2 value from inside this function as it may not be the latest.

如果您对由useState创建的更新功能是否同步感到好奇,即,如果React在使用钩子时批处理状态更新,请

If you are curious about whether the update function created by useState is synchronous, i.e. if React batches the state update when using hooks, this answer provide some insight into it.

这篇关于useState是同步的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆