简体   繁体   English

为什么 event.target.value 在运行 await 后没有更新?

[英]Why event.target.value is not updated after running await?

I'm writing a onChange event handler that runs with some async codes.我正在编写一个使用一些异步代码运行的 onChange 事件处理程序。 Since the function is asynchronous, event object has persisted at the top.由于该函数是异步的,事件对象一直存在于顶部。

Before running await , 'event.targe.value' is expected, but after running await, event.target.value is not updated.在运行await之前, 'event.targe.value' 是预期的,但是在运行 await 之后, event.target.value 不会更新。

I know that I can cache value like const value = event.targe.value before running await, but I want to know why the event.target.value changes before and after await.我知道我可以在运行 await 之前缓存像const value = event.targe.value这样的const value = event.targe.value ,但我想知道为什么 event.target.value 在 await 之前和之后会发生变化。

function MyApp() {
  const [title, setTitle] = useState('')
  
  const handleChange = async (e) => {
    // if I type 'a' 
    console.log(e.target.value) // 'a'
    e.persist()
    console.log(e.target.value) // 'a'

    // some async code here
    await Promise.resolve(null)

    console.log(e.target.value) // value is not 'a' but '', not updated
    setTitle(e.target.value)
  }

  return <input value={title} onChnage={handleChange} />
}

Event handlers will be passed instances of SyntheticEvent . Event handlers将传递SyntheticEvent实例。

The SyntheticEvent is pooled. SyntheticEvent 被合并。 This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked.这意味着 SyntheticEvent 对象将被重用,并且在调用事件回调后所有属性都将被取消。

If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.如果您想以异步方式访问事件属性,您应该对事件调用 event.persist(),这将从池中删除合成事件并允许用户代码保留对事件的引用。
-- React Docs -- 反应文档

Using e.persist() allows you to fetch the event.target.value in the async function:使用e.persist()允许您在 async 函数中获取event.target.value

const handleChange = async (e) => {
    e.persist()
    // async function
    await new Promise((resolve) => {
      console.log('async', e.target.value) // you can get the value here
      resolve()
    })

    console.log(e.target.value) // but not here
  }

Also, checkout this answer here .另外,请在此处查看此答案。

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

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