react 生命周期实例分析
本文实例讲述了react生命周期。分享给大家供大家参考,具体如下:
组件挂载:
componentWillMount(组件将要挂载到页面)->render(组件挂载中)->componentDidMount(组件挂载完成后)
组件更新:
1、shouldComponentUpdate(render之前执行,参数为ture时执行render,为false时不执行render)
componentWillUpdate(shouldComponentUpdate之后执行)
componentDidUpdate(render之后执行)
顺序:shouldComponentUpdate-》componentWillUpdate-》render-》componentDidUpdate
importReact,{Component,Fragment}from'react';
importListfrom'./List.js';
classTestextendsComponent{
constructor(props){
super(props);
this.state={
inputValue:'aaa',
list:['睡觉','打游戏'],
}
//this.add=this.add.bind(this);
}
addList(){
this.setState({
list:[...this.state.list,this.state.inputValue],
inputValue:''
})
}
change(e){
this.setState({
//inputValue:e.target.value
inputValue:this.input.value
})
}
delete(i){
//console.log(i);
constlist=this.state.list;
list.splice(i,1);
this.setState({
list:list
})
}
//组件将要挂载到页面时
componentWillMount(){
console.log('componentWillMount');
}
//组件完成挂载后
componentDidMount(){
console.log('componentDidMount');
}
//组件被修改之前,参数为ture时执行render,为false时不往后执行
shouldComponentUpdate(){
console.log('1-shouldComponentUpdate');
returntrue;
}
//shouldComponentUpdate之后
componentWillUpdate(){
console.log('2-componentWillUpdate');
}
//render执行之后
componentDidUpdate(){
console.log('4-componentDidUpdate');
}
//组件挂载中
render(){
console.log('3-render');
return(
{this.input=input}}value={this.state.inputValue}onChange={this.change.bind(this)}/>
添加
{
this.state.list.map((v,i)=>{
return(
);
})
}
);
}
}
exportdefaultTest;
2、componentWillReceiveProps(子组件中执行。组件第一次存在于虚拟dom中,函数不会被执行,如果已经存在于dom中,函数才会执行)
componentWillUnmount(子组件在被删除时执行)
importReact,{Component}from'react';
importPropTypesfrom'prop-types';
classListextendsComponent{
constructor(props){
super(props);
this.delete=this.delete.bind(this);
}
//组件第一次存在于虚拟dom中,函数不会被执行
//如果已经存在于dom中,函数才会执行
componentWillReceiveProps(){
console.log('componentWillReceiveProps');
}
//子组件被删除时执行
componentWillUnmount(){
console.log('componentWillUnmount');
}
render(){
return(
组件性能优化:
importReact,{Component}from'react';
importPropTypesfrom'prop-types';
classListextendsComponent{
constructor(props){
super(props);
this.delete=this.delete.bind(this);
}
//组件第一次存在于虚拟dom中,函数不会被执行
//如果已经存在于dom中,函数才会执行
componentWillReceiveProps(){
console.log('componentWillReceiveProps');
}
//子组件被删除时执行
componentWillUnmount(){
console.log('componentWillUnmount');
}
shouldComponentUpdate(nextProps,nextState){
if(nextProps.content!==this.props.content){
returntrue;
}else{
returnfalse;
}
}
render(){
return(
希望本文所述对大家react程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。