git地址:https://github.com/limin0309/React_Life.git 仅限个人留用
父组件
import React from 'react';
import Child from './child'
export default class Life extends React.Component{
constructor(props){
super(props);
this.state={
count:0
}
}
handleAdd=()=>{
this.setState({
count:this.state.count+1
})
}
render(){
return <div>
<p>react生命周期</p>
<button onClick={this.handleAdd}>点击一下</button>
<p>{this.state.count}</p>
<Child count={this.state.count}></Child>
</div>
}
}
- 父组件向子组件传值通过this.state 子组件接收副组件传值通过this.props 如:
<Child count={this.state.count}></Child>
子组件:
import React from 'react';
export default class Child extends React.Component{
constructor(props){
super(props);
}
// 笔记-生命周期依次执行
// willMount
// didMount
// 当发生改变时:
// willReceiveProps zhansgan1
// shouldComponentUpdate
// componentWillUpdate
// componentDidUpdate
// 父--子 this.state 子--父 this.props
componentWillMount(){
console.log('willMount')
}
componentDidMount(){
console.log('didMount')
}
componentWillReceiveProps(nextProps){
console.log('willReceiveProps'+ this.props.count)
}
shouldComponentUpdate(){
console.log('shouldComponentUpdate')
return true
}
componentWillUpdate(){
console.log('componentWillUpdate')
}
componentDidUpdate(){
console.log('componentDidUpdate')
}
render(){
return <div>
<p>子组件</p>
<span>{this.props.count}</span>
</div>
}
}
- React生命周期:
componentWillMount
componentDidMount
当发生改变时:
componentWillReceiveProps zhansgan1
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
···介绍:
getDefultProps 通过这个方法 初始化一个props属性,这个props来自于父组件/其他组件传递过来的东西
getInitalState 初始化当前组件的状态,state状态会贯穿整个项目当中,用 setState等调整
componentWillMount 组件加载前会调用—初始化的时候调用接口,可以在willMount中调用
render 最多,最频繁的最重要的方法,ui和元素出来都是在render
componentDidMount 组件加载后会调用—组件更新完,setState,再去更新状态
componentWillReceiveProps父组件组件的传递会调用的方法,接受属性
shouldComponentUpdate 组件要更新,调用setState就调用这个
componentWillUpdate 组件要更新之前
componentDidUpdate组件更新之后
componentWillUnmount组件要销毁
···