React知识点——state总结
1.state组件理解
理解
1) state是组件对象中最重要的属性,值是对象(可以包括多个key-value的组合)
2)组件被称为"状态机",通过更新组件的state来更新对应的页面显示(重新渲染组件)
注意
1)组件中render方法中的this为组件实例对象
2)组件自定义的方法中this为underfined,如何解决?
a. 强制绑定this:通过函数对象 bind()
b.使用箭头函数
比如:
// 自定义方法————要用复制语句的形式+箭头函数
changeWeather=()=>{
constisHot=this.state.isHot
this.setState({isHot:!isHot})
}
3)状态函数不能直接更新,必须使用setState
state
isHot:true
wind:"jojo的奇妙冒险"
======================
this.setState({isHot:!isHot})
!!这里要注意第二个S要大写!!
附加:
上一篇的代码很复杂,格式没错,但是很麻烦,要改善的话应该是这样改善
简化后:
// 1.创建组件
classWeatherextendsReact.Component{
// 初始化状态
state={isHot:false,wind:'微风'}
render() {
const{isHot}=this.state
return(今天天气真的很{this.state.isHot?'炎热':'凉爽'})
}
// 自定义方法————要用复制语句的形式+箭头函数
changeWeather=()=>{
constisHot=this.state.isHot
this.setState({isHot:!isHot})
}
}
// 2.渲染组件到页面
ReactDOM.render(,document.getElementById('test'))
对比之前的代码:
// 1.创建组件
classWeatherextendsReact.Component{
constructor(props) {
super(props)
this.state={isHot:true,wind:"微风"}
this.changeWeather=this.changeWeather.bind(this)
}
render() {
const{isHot}=this.state
return(今天天气很{this.state.isHot?'炎热':'凉爽'})
}
changeWeather() {
constisHot=this.state.isHot
this.setState({isHot:!isHot})
}
}
// 2.渲染组件到页面
ReactDOM.render(,document.getElementById('test'))
构造器咱们可以不用写,只用到state,就只初始化state。
// 初始化状态
state =
//创建构造器
constructor(props) {
super(props)
this.state = { isHot: true, wind: "微风" }
this.changeWeather = this.changeWeather.bind(this)
}
效果是一样的,上面的会不会是更简单一些。再就类实例对象中方法的调用。
// 自定义方法————要用复制语句的形式+箭头函数
changeWeather=()=>{
constisHot=this.state.isHot
this.setState({isHot:!isHot})
}
}
这里代表的2个方法
a. 强制绑定this:通过函数对象 bind()
b.使用箭头函数
箭头函数代码量更加的少更加的精简,那么代码就整洁简化了。
声明:以上内容并不代表本网赞同其观点。如有任何问题,请与不良与违法信息举报中心联系:513175919@qq.com。