状态 state

未匹配的标注

基础

简介

  • state 状态可以理解为组件内部数据的一种载体, 通过改变 state 中的数据, 页面就会更新, 从而就不用通过操作 dom
  • 不能直接修改状态中的数据, 要通过 setState 来改变, 如 this.state.username = 'xiaoming'
  • 也不能直接赋值 (浅拷贝) 然后改变数据, 如 todo list 案例中, 要使用深拷贝

基本用法

  • 数据都包含在 state 的对象中, 其中 state 变量名不可以改变, 是固定的
  • 写法1
import React, {Component} from 'react';

class App extends Component {
  state = {
    isCollect: false
  }

  render() {
    return (
      <div>
        <p>{this.state.isCollect ? '取消收藏' : '收藏'}</p>
        <button onClick={() => {
          this.setState({
            isCollect: !this.state.isCollect
          })
        }}>collect</button>
      </div>
    );
  }
}

export default App;
  • 写法2
class App extends Component {
  constructor() {
    super();
    this.state = {
      isCollect: false
    }
  }

  render() {
    return (
      <div>
        <p>{this.state.isCollect ? '取消收藏' : '收藏'}</p>
        <button onClick={() => {
          this.setState({
            isCollect: !this.state.isCollect
          })
        }}>collect</button>
      </div>
    );
  }
}

同步异步

  • react18之后 ( 包含 react18 ), setState 就都是异步更新, 即多次调用 setState 得到的结果是同一个
  • react18 之前, setState 处在同步代码中时, 是异步更新; 在异步代码中, 则是同步更新
  • 如果想要在 setState 执行完后, 立马拿到执行后的结果, 则可以在 setState 中再添加一个回调函数, 在回调函数中可以立马拿到更新后的结果
import React, {Component} from 'react';

class App extends Component {
  state = {
    count: 1
  }

  handlerAdd1 = () => {
    // 只会执行一遍 setState
    this.setState({
      count: this.state.count + 1
    }, () => {
      console.log(this.state.count); // 2
    })

    this.setState({
      count: this.state.count + 1
    })

    this.setState({
      count: this.state.count + 1
    })
  }

  handlerAdd2 = () => {
    // react18 中全部都是异步更新了, react18 以前, 以下则是同步更新
    setTimeout(() => {
      this.setState({
        count: this.state.count + 1
      })
      console.log(this.state.count);

      this.setState({
        count: this.state.count + 1
      })
      console.log(this.state.count);

      this.setState({
        count: this.state.count + 1
      })
      console.log(this.state.count);
    }, 0)
  }

  render() {
    return (
      <div>
        <p>{this.state.count}</p>
        <button onClick={this.handlerAdd1}>add1</button>
        <button onClick={this.handlerAdd2}>add2</button>
      </div>
    );
  }
}

export default App;

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~