生命周期创建时:
创建时 cconstructor -> render -> componentDidMount
class App extends React.Component {
渲染页面完成前
constructor(props) {
super(props)
console.log('App constructor 执行');
1、初始化state
this.state = {
count:0
}
2、绑定事件函数
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
console.log('点击事件函数');
}
渲染页面
setState 一旦修改成功,render会执行一次
render里不能修改setState: (render 中要是使用setState会陷入死循环)
render() {
console.log('App render 执行');
return (
<div onClick={this.handleClick}>App</div>
)
}
渲染完成
componentDidMount() {
console.log('App componentDidMount 执行');
document.ready | $(function(){}) 当页面渲染完成时
1、发送网络请求: ajax axios fetch...
2、DOM操作: document.querySelector()...
}
}
生命周期更新时
更新时触发条件
1、有新的props传入
2、setState方法被调用(只有组件本身的setState,才能触发组件的更新事件,不会更新其他组件的更新事件)
3、forceUpdate(强制重新渲染)执行
更新时,执行 render -> componentDidUpdate
class App extends React.Component {
渲染页面完成前
constructor(props) {
super(props)
console.log('App constructor 执行');
1、初始化state
this.state = {
count: 0
}
2、绑定事件函数
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
1、修改count值,以新的props传入Child子组件
this.setState(state => {
return {
count: state.count + 1
}
})
}
render() {
console.log('App render 执行');
return (
<div onClick={this.handleClick}>
App:{this.state.count}
<Child count={this.state.count} />
</div>
)
}
componentDidUpdate() {
console.log('App componentDidUpdate 执行')
}
}
class Child extends React.Component {
state = {
name: '张三'
}
更新完成后执行该函数
componentDidUpdate() {
componentDidUpdate 可以完成的事件:
1、发送网络请求:
2、DOM操作(setState必须放在if里)
console.log('Child componentDidUpdate 执行')
}
通过setState事件,改变state,也会触发更新
childClick = () => {
this.setState(state => {
return {
name: '李四'
}
})
强制重新渲染
this.forceUpdate()
}
render() {
console.log('Child render 执行')
return (<div onClick={this.childClick}>子组件{this.state.name}</div>)
}
}
生命周期卸载时:
class App extends React.Component {
state = {
show: true
}
handleClick = () => {
this.setState(state => {
return { show: !state.show }
})
}
render() {
return (
<div>
父组件<br />
<button onClick={this.handleClick}>切换子组件</button>
{/* 为 null 什么都不显示*/}
{/*this.state.show ? (<Child />) : null*/}
{this.state.show && <Child />}
</div>
)
}
}
class Child extends React.Component {
卸载生命周期
一旦组件消失就会调用这个函数
componentWillUnmount() {
console.log('Child componentWillUnmount 执行');
}
render() {
return (<h3>子组件</h3>)
}
}