04 - react中的state(组件核心属性)

1,106 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第4天,点击查看活动详情

state 本有状态之意,在react中需管理数据状态,此时state就诞生了。state可以存储数据供组件实例对象使用,值为一个对象,在其数据改变时,reac会监听重新调用生命周期中 render 函数,随之页面重新渲染。

用下面这个案例来介绍使用下state

一、案例:点击按钮加1

  1. 定义组件
<script type="text/babel">

  class Counts extends React.Component {
    // 定义state,值为对象,key - value
    state = { 
       count: 0 
    }

    render() {
      const { count } = this.state
      return (
        <div>
          当前数:{count} <br/>
          <button> +1 </button>
        </div>
      )
    }
  }

  ReactDOM.render(<Counts/>, document.getElementById('demo'))

</script>

image.png

  1. 添加按钮事件

添加addCount函数,改变state需要使用setState函数,react监听state,改变重新渲染dom。

class Counts extends React.Component {

  state = {
    count: 0
  }

  addCount = () => {
    let { count } = this.state
    count += 1
    this.setState({ count })
  }

  render() {
    const { count } = this.state
    return (
      <div>
        当前数:{count} <br/>
        <button onClick={this.addCount}> +1 </button>
      </div>
    )
  }
}

image.png

image.png

  1. setState

更新修改state,不能直接更新,需要调用setState(),直接更新页面不会重新渲染。state 的更新会被合并,当调用 setState() 的时候,React 会把你提供的对象合并到当前的 state。