简体   繁体   English

React Hooks SetState 是异步的吗?

[英]Is React Hooks SetState async?

I have a question regarding hooks and set State.我有一个关于钩子和设置 State 的问题。 Let's take very basic example.让我们举一个非常基本的例子。 Suppose I have one input box and button, which is a very common use case.假设我有一个输入框和按钮,这是一个非常常见的用例。 Whenever i type in input box, and click on button, button click handler should reflect the latest state.每当我在输入框中键入并单击按钮时,按钮单击处理程序应反映最新的 state。 On stackoverflow, I saw below code to do the activity:在stackoverflow上,我看到下面的代码来做这个活动:

const input = props => {  
  const [textInput, setTextInput] = React.useState('');

  const handleClick = () => {
    console.log(textInput);
    props.send(textInput);
  }

  const handleChange = (event) => {
    setTextInput(event.target.value);
  }

  return (
    <div>
      <input onChange={handleChange} placeholder="Type a message..." />
      <div onClick={handleClick} className="icon">
        <i className="fa fa-play" />
      </div>
    </div>
  )
} 

Isnt above setTextInput(event.target.value);不在 setTextInput(event.target.value); 之上input async as react does batching?输入异步作为反应做批处理? So when user clicks on submit, how do i know that state is actually updated?那么当用户点击提交时,我怎么知道 state 实际更新了? . . This is a very basic use case and i don't want to use useRef as this must be a common problem or am i missing something?这是一个非常基本的用例,我不想使用 useRef,因为这一定是一个常见问题,或者我错过了什么?

Note: In above solution, we want to read the state only after both the conditions are satisfied:注意:在上述解决方案中,我们要在两个条件都满足后才能读取 state:

  1. User has clicked button.用户已单击按钮。
  2. State has been updated by setState State 已由 setState 更新

In my limited knowledge, setState is in fact asynchronous.在我有限的知识中, setState实际上是异步的。 It does not interrupt other processes to carry out setting the state.它不会中断其他进程来执行设置 state。 It is queued to be executed on the next batch.它排队等待下一批执行。

The situation you are talking about here will never have the async nature of setState cause problems.您在这里谈论的情况永远不会有setState的异步性质导致问题。 The action of the user clicking will always happen after the newState is set.用户点击的动作总是在设置 newState 之后发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM