欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

React的setState()

程序员文章站 2024-03-02 15:55:40
...

 注释掉   this.setState({val: this.state.val + 6}) 时:

React的setState()

不注释掉   this.setState({val: this.state.val + 6}) 时:

React的setState() 

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor(porps) {
    super(porps);
    this.state = {
      val: 0
    };
  }
  componentDidMount() {
    this.setState(this._increment);
    this.setState(this._increment);
    //this.setState({val: this.state.val + 6});
    this.setState(this._increment);
    console.log('componentDidMount:')
    console.log(this.state);    
  }
  _increment(state, props){
    console.log('_increment:')
    console.log(state);
    return {val: state.val + 1};
  }  
  render() { 
    console.log('render:')
    console.log(this.state);    
    return (
      <div className="App">
        <div>{this.state.val}</div>
      </div>
    );
  }
}

export default App;

 this.setState()是异步的,render()会等这几个setState的异步函数都执行完(包括需要异步执行的代码)才会执行