简体   繁体   中英

What does async setState mean?

Consider TextInput in react-native, below implementation seems to be a standard approach:

<TextInput
  value={this.state.text}
  onChangeText={text => this.setState({ text })}
/>

However, setState() is an async function. I am wondering whether it is possible to encounter inconsistency due to the execution order of setState().

For example:

  1. Type 'ab'
  2. setState({ text: 'ab' })
  3. setState({ text: 'a' })
  4. this.state.text results in 'a'

setState() is an async function. Whether it is possible to encounter inconsistency due to the execution order of setState()

Async setState() does not mean that setState will be called in any random order. setState is async means it will just update the state asynchronously.

In your case whenever some key is pressed onChange handler will be called and that will call setState which means setState will be called sequentially on every key press and will update the state in same sequence but asynchronously .

try

<TextInput
   onChange={(e) => this.setState({ text : e.target.value })}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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