- 在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>
}
}