三、React学习笔记整理(组件核心属性State)

134 阅读1分钟

什么是State

     React是由数据驱动的一个框架,数据发生变化,页面就会发生变化,数据来自组件外部的props或组件内部的state。而保存在组件state中的数据仅供组件内部使用。

  • 函数式组件没有状态
  • 只有类式组件才有状态 最新版的React⾥⾯有hooks, 让函数式组件也能使⽤状态

初始化State

// 1.天气组件
class Weather extends React.Component{
  constructor(props){
    super(props);
    // 初始化组件状态
    this.state = {
      isHot: true
    }
  }
  render() {
    console.log(this);
    const{isHot} = this.state
    return (
      <div>
          今天天气很{isHot === true ? '炎热' : '凉爽'}
      </div>
    );
  }
}
// 2.渲染组件到页面
ReactDOM.render(<Weather/>, document.getElementById('test'))

setState

通过setState修改state中的属性值

// 1.天气组件
class Weather extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      isHot: true,
      wind: '大风'
    }
    this.changeWeather = this.changeWeather.bind(this)
  }

  changeWeather(){
    // 在这里直接修改state不会渲染到页面上,需要通过setState修改
    // this.state.isHot = !this.state.isHot
    // setState是一个合并操作并不是替换操作
    this.setState({isHot: !this.state.isHot})
  }
  render() {
    console.log('render this', this);
    const{isHot, wind} = this.state
    return (
      <div id="title" onClick={this.changeWeather}>
          今天天气很{isHot === true ? '炎热' : '凉爽'},{wind}
      </div>
    );
  }
}
ReactDOM.render(<Weather/>, document.getElementById('test'))

State的简写方式

class Weather extends React.Component{
  // 第一步将state从构造方法中提取出来(因为直接在类中写的属性,会作为每个实例的默认属性存在着)
  state = {
    isHot: true,
    wind: '大风'
  }
  // 第二步使用箭头函数,就不需要使用bind改变this指向了(因为箭头函数没有this的概念,它就会向上去找同级别的this)
  changeWeather = () => {
    console.log('changeWeather', this);
    this.setState({isHot: !this.state.isHot})
  }
  render() {
    console.log('render this', this);
    const{isHot, wind} = this.state
    return (
      <div id="title" onClick={this.changeWeather}>
          今天天气很{isHot === true ? '炎热' : '凉爽'},{wind}
      </div>
    );
  }
}
    ReactDOM.render(<Weather/>, document.getElementById('test'))