React学习-constructor的使用

  • 在react挂载之前,会调用它的构造函数。在为React.Component子类实现构造函数时,应在其他语句之前调用super(props)。否则,this.props在构造函数中可能会出现未定义的bug。
  • 构造器是否接收props,是否传递给super,取决于:是否希望在构造器中通过this访问props
class Weather extends React.Component{
  constructor(props){
	super(props)
	//初始化状态
	this.state = {isHot:false,wind:'微风'}
	//解决changeWeather中this指向问题
	this.changeWeather = this.changeWeather.bind(this)
  }
  changeWeather(){
	//changeWeather放在哪里? ———— Weather的原型对象上,供实例使用
	//由于changeWeather是作为onClick的回调,所以不是通过实例调用的,是直接调用
	//类中的方法默认开启了局部的严格模式,所以changeWeather中的this为undefined	
	//获取原来的isHot值
	const isHot = this.state.isHot
	//严重注意:状态必须通过setState进行更新,且更新是一种合并,不是替换。
	this.setState({isHot:!isHot})
	//严重注意:状态(state)不可直接更改,下面这行就是直接更改!!!
	//this.state.isHot = !isHot //这是错误的写法
}
  render(){
	 const {isHot,wind} = this.state
	 return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'}{wind}</h1>
  }
}

无论有没有constructor,在render中this.props都是可以使用的,这是React自动附带的)
以上代码可简写为以下这种方式,这么做就可以省略constructor()。

class Weather extends React.Component{
	//初始化状态
	state = {isHot:false,wind:'微风'}
	//changeWeather = this.changeWeather.bind(this)
    //changeWeather(){
    //	const isHot = this.state.isHot
    //	this.setState({isHot:!isHot})
    //}
	//使用箭头函数也可解决this丢失问题
	//原因:箭头函数的this时在定义函数时绑定的,不是在执行过程中绑定的。简单的说,函数在定义时,this就是继承了定义函数的对象。
   changeWeather = ()=>{
	 const isHot = this.state.isHot
	 this.setState({isHot:!isHot})
   }
  render(){
	 const {isHot,wind} = this.state
	 return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'}{wind}</h1>
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值