react的生命周期
1、 static defaultProps
静态属性中设置默认属性,在没有设置的情况下走默认设置
2、 constructor
构造函数使用需要super();的配合 ,若没有super()的配合会报错
在这里面设置状态 this.state ===> this.state = {name:“Lily”} 后面是对象
3、componentWillMount
组件经过上面的步骤初始化数据后,将要渲染组件
在组件渲染之前我们可以做些什么,在这里进行设置
一般用的比较少
不建议在这处使用AJAX请求
4、render
组件根据render里return后面的内容进行渲染,将react生成的虚拟DOM结构渲染成真实的DOM结构
return后面若要换行需要用( ) 括起来
render(){
return (
<div>
<p>我好像是一个子组件</p>
<p>{this.props.n}</p>
</div>
)
}
5、componentDidMount
组件渲染完成,这是的DOM节点生成,可以在这个地方发起AJAX请求,通过setState后更换数据,组件重新渲染
6、shouldComponentUpdate(nextProps,nextState)
组件是否需要更新
shouldComponentUpdate(nextProps,nextState){
//下一个的属性 下一个状态
console.log("4.父组件是否需要更新");
console.log(this.state.number);
return nextState.number%2
//return 后结果为true则更新
//若为false则不更新
}
7、componentWillUpdate(nextProps,nextState)
在shouldComponentUpdate返回true以后,组件重新进入到渲染的流程,在更新之前做点什么
8、componentDidUpdate
组件更新完成之后做什么
9、componentWillUnmount
组件卸载
这里可以清除定时器,移除所有的监听事件
10、4.componentWillReceiveProps (nextProps)
componentWillReceiveProps(newProps){
//父组件第一次渲染时不被触发
//只有父组件再次渲染时才会触发
console.log(将要接收父组件传的属性")
console.log(newProps);
return newProps.n%3;
}
//return 为true接收属性
对于这些生命周期 在使用的时候建议都输出下arguments看看到底有哪些属性,我们操作的时候又需要哪些属性
import React,{Component} from 'react';
import ReactDOM,{render} from 'react-dom';
class Hello extends Component{
static defaultProps = {
name:"zf"
};
constructor(){
super();
this.state = {number:0}
}
handleClick = ()=>{
this.setState({number:this.state.number+1})
};
componentWillMount(){
console.log("1.父组件将要渲染");
};
componentDidMount(){
console.log("3.父组件渲染完成");
};
componentWilUnmount(){
console.log("父组件要卸载");
};
shouldComponentUpdate(nextProps,nextState){//下一个的属性 下一个状态
console.log("4.父组件是否需要更新");
console.log(this.state.number);
return nextState.number%2 //return 后结果为true则更新,若为false则不更新
}
componentWillUpdate(){
console.log("5.父组件将要更新");
}
componentDidUpdate(){
console.log("6.父组件更新完成");
}
destroy(){
ReactDOM.unmountComponentAtNode(window.root)//移除挂载在root下的组件
}
render(){
console.log("2.父组件渲染");
return (
<div>
{this.props.name}
<p>{this.state.number}</p>
<button onClick={this.handleClick}>按钮</button>
{this.state.number<3?<Child n={this.state.number}/>:null}
</div>
)
}
}
class Child extends Component{
componentWillMount(){
console.log("1.子组件将要渲染");
}
componentDidMount(){
console.log("3.子组件渲染完成");
}
componentWillReceiveProps(newProps){ //父组件第一次渲染时不被触发,只有父组件再次渲染时才会触发
console.log("4.将要接收父组件传的属性",newProps);
return newProps.n%3;
}
shouldComponentUpdate(newProps,nextState){
console.log("5.子组件是否需要更新");
return newProps.n%3
}
componentWillUpdate(){
console.log("6.子组件将要更新");
}
componentWillUnmount(){
console.log("7.子组件将要销毁");
}
render(){
console.log("2.子组件渲染");
return (
<div>
<p>我好像是一个子组件</p>
<p>{this.props.n}</p>
</div>
)
}
}
ReactDOM.render(<Hello/>,window.root);