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

查看:63
本文介绍了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');

不会导致运行回调.

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

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])

上面的 useEffect 只会在 state1 更新时被调用,你不应该相信这个函数内部的 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是否在使用hook时批量更新状态,这个答案 提供了一些见解.

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天全站免登陆