一、理解
state
是组件对象最重要的属性,值是对象(可以包含多个key-value
的组合)- 组件被称为“状态机”,通过更新组件的
state
来更新对应的页面显示(重新渲染组件)
效果展示:
简化后代码:
//1.创建组件
class Weather extends React.Component{
//初始化状态
state = {isHot:false,wind:'微风'}
//render调用几次? ———— 1+n次 1是初始化的那次 n是状态更新的次数
render(){
const {isHot,wind} = this.state
return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h1>
}
//自定义方法————要用赋值语句的形式+箭头函数
changeWeather = ()=>{
//获取原来的isHot值
const isHot = this.state.isHot
//严重注意:状态必须通过setState进行更新,且更新是一种合并,不是替换。
this.setState({isHot:!isHot})
//严重注意:状态(state)不可直接更改,下面这行就是直接更改!!!
//this.state.isHot = !isHot //这是错误的写法
}
}
//2.渲染组件到页面
ReactDOM.render(<Weather/>,document.getElementById('test'))
二、注意
- 组件中
render
方法中的this
为组件实例对象 - 组件自定义的方法
this
为undefined
,如何解决?
a. 强制绑定this:
通过函数对象的bind()
b. 箭头函数 - 状态数据,不能直接修改或更新