react生命周期
1,组件初次渲染
2,组件更新
3,组件shouldComponentUpdate 为fasle时
不会向下继续执行
4,组件进行forceUpdate强制跟新
注意: forceUpdate、componentDidUpdate 这两个使用场景不多,写出来供大家参考
5,代码
import React, { Component } from 'react'
export class index extends Component {
constructor(){
super()
console.log('---constructor---')
}
state = {
compName: 'react',
inputValue: ''
}
componentDidMount(){
// 组件挂载时的回调,一般请求,消息订阅,开启定时器
console.log('---componentDidMount---')
}
componentDidUpdate(){
// 组件更新时的回调
console.log('---componentDidUpdate---')
}
shouldComponentUpdate(){
// 如果写了这个函数,就必须有布尔值的返回。返回false,则不会进行更新
console.log('---shouldComponentUpdate---')
return true
}
componentWillUnmount(){
// 组件卸载时的回调,卸载时 取消将定时器,取消订阅
console.log('---componentWillUnmount---')
}
updateState(){
// 1, onClick = {this.updateState 这种写法updateState里面的函数this指向undefined,因为button里没有this,需要bind拿到构造函数的this,才能正常运行
// console.log(this,'this') //undefined
// 2, onClick = {this.updateState.bind(this)} bind拿到构造函数的this,然后传递给此函数
// 2, onClick = {this.updateState()} 这种写法组件需要写成高阶组件。因为还没有点击的时候就调用函数了,如果不写成箭头函数,函数返回的得到的值就是一个字符串,不会触发setState的运行;用箭头函数的好处,拿到的this是构造器的this,能访问到state
/*return (()=>{
this.setState({compName:'vue'})
})*/
// 3,onClick = {() => this.updateState() 这种写法直接可以调用,因为箭头函数此时拿到的this为构造函数的this,传递进来的也是
this.setState({compName:'update-react'})
}
updateForce(){
// 强制更新,不管shouldComponentUpdate返回值是否为true,都会执行这个生命钩子
console.log('---forceUpdate---')
this.forceUpdate()
}
// 表单输入拿到本身的值
getInputValue(event){
console.log(event.target.value,'event')
// 一种对象的结构方法,注意:这里的target并没有被解构出来。
const {target:{value}} = event
this.setState({inputValue:value})
}
render() {
console.log('---render---') // render首次渲染,之后每次会根据数据的更新来进行渲染
const { compName , inputValue } = this.state
return (
<div>
{/* <button onClick = {this.updateState}>点击更新状态</button> */}
{/* <button onClick = {this.updateState.bind(this)}>点击更新状态</button> */}
{/* <button onClick = {this.updateState()}>点击更新状态</button> */}
<button onClick = {() => this.updateState()}>点击更新状态</button>
<button onClick = {() => this.updateForce()}>强制跟新</button>
<div>{compName}</div>
<input type="text" onChange = {(event)=> this.getInputValue(event)}/>
<div>{inputValue}</div>
</div>
)
}
}
export default index