React进阶:setState()的同步、异步、多次调用

setState()的同步、异步、多次调用

一、01_setState()的使用

1.setState()更新状态的2种写法

1). setState(updater, [callback]),
    updater为返回stateChange对象的函数: (state, props) => stateChange
    接收的state和props被保证为最新的
2). setState(stateChange, [callback])
    stateChange为对象,
    callback是可选的回调函数, 在状态更新且界面更新后才执行

2. 总结:

    对象方式是函数方式的简写方式
        如果新状态不依赖于原状态 ===> 使用对象方式
        如果新状态依赖于原状态 ===> 使用函数方式
    如果需要在setState()后获取最新的状态数据, 在第二个callback函数中读取
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>01_setState()的使用</title>
</head>
<body>
<div id="example"></div>

<script type="text/javascript" src="./js/react.development.js"></script>
<script type="text/javascript" src="./js/react-dom.development.js"></script>
<script type="text/javascript" src="./js/babel.min.js"></script>
<script src="https://cdn.bootcss.com/remarkable/1.7.1/remarkable.min.js"></script>

<script type="text/babel">
  class A extends React.Component {
    state = {
      count: 1
    }

    test1 = () => {
      this.setState(state => ({count: state.count + 1}))
      console.log('test1 setState()之后', this.state.count) //输出:1
    }

    test2 = () => {
      /*const count = this.state.count + 1
      this.setState({
        count
      })*/
      this.setState({
        count: 3
      })
      console.log('test2 setState()之后', this.state.count) //输出:1
    }

    test3 = () => {
      this.setState(state => ({count: state.count + 1}), () => { // 在状态更新且界面更新之后回调
        console.log('test3 setState callback()', this.state.count) //输出2
      })
    }

    render() {
      console.log('A render()')
      return (
        <div>
          <h1>A组件: {this.state.count}</h1>
          <button onClick={this.test1}>A 测试1</button>&nbsp;&nbsp;
          <button onClick={this.test2}>A 测试2</button>&nbsp;&nbsp;
          <button onClick={this.test3}>A 测试3</button>&nbsp;&nbsp;
        </div>
      )
    }
  }

  ReactDOM.render(<A/>, document.getElementById('example'))
</script>
</body>
</html>

二、02_setState()异步OR同步更新

1. setState()更新状态是异步还是同步的?

  1). 执行setState()的位置?
      在react控制的回调函数中: 生命周期勾子 / react事件监听回调  => 异步
      非react控制的异步回调函数中: 定时器回调 / 原生事件监听回调 / promise回调 /... => 同步

2.关于异步的setState()

  1). 多次调用, 如何处理?
      setState({}): 合并更新一次状态, 只调用一次render()更新界面 ---状态更新和界面更新都合并了
      setState(fn): 更新多次状态, 但只调用一次render()更新界面  ---状态更新没有合并, 但界面更新合并了
  2). 如何得到异步更新后的状态数据?
      在setState()的callback回调函数中

3.为什么在react相关调用中是异步,其它是同步?

在react中用到了【事务】,它存在就是异步,而react之外未用到【事务】所以就是同步。

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>02_setState()异步OR同步更新</title>
</head>
<body>

<div id="example"></div>

<script type="text/javascript" src="./js/react.development.js"></script>
<script type="text/javascript" src="./js/react-dom.development.js"></script>
<script type="text/javascript" src="./js/babel.min.js"></script>

<script type="text/babel">
  class StateTest extends React.Component {
    state = {
      count: 0,
    }

    /*
     【异步】react事件监听回调中, setState()是异步更新状态
     */
    update1 = () => {
      console.log('update1 setState()之前', this.state.count) // =>0
      this.setState(state => ({count: state.count + 1}))
      console.log('update1 setState()之后', this.state.count) // =>0
    }

    /*
     react生命周期勾子中, setState()是异步更新状态(在其它函数运行时,此处注释掉)
     
    componentDidMount () {
      console.log('componentDidMount setState()之前', this.state.count) //=>0
      this.setState(state => ({count: state.count + 1}))
      console.log('componentDidMount setState()之后', this.state.count) //=>0
    }*/

    /*
    【同步】定时器回调 / 原生事件监听回调 / promise回调 /...
     */
    update2 = () => {//同步
      setTimeout(() => {
        console.log('setTimeout setState()之前', this.state.count) // 0
        this.setState(state => ({count: state.count + 1}))
        console.log('setTimeout setState()之后', this.state.count) // 1
      },1000) //1秒后执行
    }
    update3 = () => {//同步
      const h2 = this.refs.count //根据ref找到h2,即页面显示的数字
      h2.onclick = () => { //点过更新按钮之后,再点h2里的数字才执行
        console.log('onclick setState()之前', this.state.count) // 0
        this.setState(state => ({count: state.count + 1}))
        console.log('onclick setState()之后', this.state.count) // 1
      }
    }
    update4 = () => {//同步
      Promise.resolve().then(value => {
        console.log('Promise setState()之前', this.state.count) //0
        this.setState(state => ({count: state.count + 1}))
        console.log('Promise setState()之后', this.state.count) //1
      })
    }


    update5 = () => {
    //setState(fn): 更新多次状态, 但只调用一次render()更新界面--状态更新没有合并, 但界面更新合并了
      console.log('onclick setState()之前', this.state.count) // 0
      this.setState(state => ({count: state.count + 1}))
      console.log('onclick setState()之后', this.state.count) // 0
      
      console.log('onclick setState()之前2', this.state.count) // 0
      this.setState(state => ({count: state.count + 1}))
      console.log('onclick setState()之后2', this.state.count) // 0
    }

    update6 = () => {
    //setState({}):合并更新一次状态, 只调用一次render()更新界面--状态更新和界面更新都合并了
      console.log('onclick setState()之前', this.state.count) // 0
      this.setState({count: this.state.count + 1})
      console.log('onclick setState()之后', this.state.count) // 0
      console.log('onclick setState()之前2', this.state.count) // 0
      this.setState({count: this.state.count + 1})
      console.log('onclick setState()之后2', this.state.count) // 0
    }

    update7 = () => {//setState({}) setState(fn)5-6混合:
      console.log('onclick setState()之前', this.state.count) // 0
      this.setState({count: this.state.count + 1})
      console.log('onclick setState()之后', this.state.count) // 0

      console.log('onclick setState()之前2', this.state.count) // 0
      this.setState(state => ({count: state.count + 1}))
      console.log('onclick setState()之后2', this.state.count) // 0
    }

   update8 = () => {//利用回调显示state更新后的值
      console.log('onclick setState()之前', this.state.count) //0
      this.setState({count: this.state.count + 1},
      ()=>{console.log('onclick setState()之后', this.state.count)})  //1             
    }



    render() {
      const {count} = this.state
      console.log('render()', count)
      return (
        <div>
          <h2 ref='count'>{count}</h2>
          <button onClick={this.update1}>更新1</button> ---
          <button onClick={this.update2}>更新2</button> &nbsp;
          <button onClick={this.update3}>更新3</button> &nbsp;
          <button onClick={this.update4}>更新4</button> ---
          <button onClick={this.update5}>更新5</button> &nbsp;
          <button onClick={this.update6}>更新6</button> &nbsp;
          <button onClick={this.update7}>更新7</button> &nbsp;
          <button onClick={this.update8}>更新8</button> &nbsp;
        </div>
      )
    }
  }

  ReactDOM.render(<StateTest/>, document.getElementById('example')) // 渲染组件标签, 内部会调用组件标签对象的render()虚拟DOM
</script>
</body>
</html>

三、setState()面试题

2(执行顺序) ==> 0(输出值)

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>03_setState()面试题</title>
</head>
<body>

<div id="example"></div>

<script type="text/javascript" src="./js/react.development.js"></script>
<script type="text/javascript" src="./js/react-dom.development.js"></script>
<script type="text/javascript" src="./js/babel.min.js"></script>

<script type="text/babel">
  class StateTest extends React.Component {

    state = {
      count: 0,
    }

    componentDidMount() {
      this.setState({count: this.state.count + 1})
      this.setState({count: this.state.count + 1})
      console.log('[1]',this.state.count) // 2 ==> 0

      this.setState(state => ({count: state.count + 1}))
      this.setState(state => ({count: state.count + 1}))
      console.log('[2]',this.state.count) // 3 ==> 0

      setTimeout(() => {
        this.setState({count: this.state.count + 1})
        console.log('timeout', this.state.count) // 10 ==> 6

        this.setState({count: this.state.count + 1})
        console.log('timeout', this.state.count) // 12 ==> 7
      }, 0)

      Promise.resolve().then(value => {
        this.setState({count: this.state.count + 1})
        console.log('promise', this.state.count)  // 6 ==>4

        this.setState({count: this.state.count + 1})
        console.log('promise', this.state.count) // 8 ==> 5
      })
    }

    render() {
      const count = this.state.count
      console.log('render', count)  // 1 ==> 0   4 ==>3   5 ==>4  7 ==>5  9 ==>6  11 ==>7
      return (
        <div>
          <p>{count}</p>
        </div>
      )
    }
  }

  ReactDOM.render(<StateTest/>, document.getElementById('example'))

</script>
</body>
</html>

源码: https://github.com/chenxi188/admin-client_final/tree/master/test

你可能感兴趣的:(前端,#,React)