Javascript useState 是同步的吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54119678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:12:12  来源:igfitidea点击:

Is useState synchronous?

javascriptreactjsreact-hooks

提问by AnilRedshift

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

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

With useState, how do I get the value of the state after explicitly updating it?

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

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

这如何与钩子一起工作?据我所知,setter 函数useState不接受回调,例如

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

doesn't result in the callback being run.

不会导致运行回调。

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 thisin strict mode).

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

回答by Claire Lin

You can use useEffectto 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 useEffectfunction:

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

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

The above useEffectwill only be called when state1is updated and you shouldn't trust the state2value from inside this function as it may not be the latest.

以上useEffect只会在state1更新时被调用,你不应该相信state2这个函数内部的值,因为它可能不是最新的。

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

如果您对创建的更新函数useState是否同步感到好奇,即 React 是否在使用钩子时批量更新状态,这个答案提供了一些洞察力。

回答by benas

Well, if you refer to the relevant docsyou'll find...

好吧,如果您参考相关文档,您会发现...

const [state, setState] = useState(initialState);

Returns a stateful value, and a function to update it.

During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).

The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

返回一个有状态的值和一个更新它的函数。

在初始渲染期间,返回的状态 (state) 与作为第一个参数 (initialState) 传递的值相同。

setState 函数用于更新状态。它接受一个新的状态值并将组件的重新渲染排入队列。

setState(newState);

During subsequent re-renders, the first value returned by useState will always be the most recent state after applying updates.

在随后的重新渲染期间, useState 返回的第一个值将始终是应用更新后的最新状态。

So your new state, whatever it is, is what you've just set in useState, i.e. the value of initialState. It goes directly to state, which updates reactively thereafter. Quoting further from the relevant docs:

所以你的新状态,不管它是什么,就是你刚刚在 中设置的useState,即 的值initialState。它直接转到state,此后响应更新。进一步引用相关文档

What does calling useState do? It declares a “state variable”. Our variable is called count but we could call it anything else, like banana. This is a way to “preserve” some values between the function calls — useState is a new way to use the exact same capabilities that this.state provides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React.

调用 useState 有什么作用?它声明了一个“状态变量”。我们的变量被称为 count 但我们可以称它为其他任何东西,比如香蕉。这是一种在函数调用之间“保留”某些值的方法——useState 是一种使用 this.state 在类中提供的完全相同功能的新方法。通常,当函数退出时变量“消失”,但状态变量被 React 保留。

If you'd like to do something whenever your state updates, then just use componentDidUpdate.(docs)

如果您想在状态更新时做某事,那么只需使用componentDidUpdate. (文档)