1.在React中,由React控制的事件处理函数,如onClick, onChange等,setState是异步的
import React, { Component } from 'react'; export default class Input extends Component { constructor(props) { super(props); this.state={ name: 'hello' } } _onChange(e) { this.setState({ name:' world' }) console.log(this.state.name); //hello } render () { return ( <div className='cp'> <input className='cp-input' value={this.state.name} onChange={this._onChange.bind(this)} type="text"/> </div> ); } }
2.在原生JS监听的事件中,如addEventListener, setState是同步的
import React, { Component } from 'react'; export default class Input extends Component { constructor(props) { super(props); this.state={ name: 'hello' } } _onChange(e) { // do something } componentDidMount() { let input = document.querySelector('.cp-input'); input.addEventListener('click', ()=>{ this.setState({ name:' world' }) console.log(this.state.name); //world }) } render () { return ( <div className='cp'> <input className='cp-input' value={this.state.name} onChange={this._onChange.bind(this)} type="text"/> </div> ); } }
3.在setTimeout中,setStatet是同步的
import React, { Component } from 'react'; export default class Input extends Component { constructor(props) { super(props); this.state={ name: 'hello' } } _onChange(e) { // do something } componentDidMount() { setTimeout(()=>{ this.setState({ name:' world' }) console.log(this.state.name); //world }, 1000) } render () { return ( <div className='cp'> <input className='cp-input' value={this.state.name} onChange={this._onChange.bind(this)} type="text"/> </div> ); } }