生命周期函数指在某一时刻组件会自动调用执行的函数
学习React,生命周期很重要,我们了解完生命周期的各个组件,对写高性能组件会有很大的帮助.
React 生命周期分为三种状态 1. 初始化 2.更新 3.销毁
组件初始化时有渲染之前 开始渲染,渲染之后生命周期,当我们要修改组件时才会触发更新的生命周期,顺序依次为确认是否修改(true or false),修改之前,开始渲染,修改之后,最后为销毁的生命周期,在组件销毁时触发
App.js组件
import React, { Component } from 'react';
//导入axios
import Life from "./Life";
class App extends Component {
constructor(props){
super(props)
this.state={
isshow:"true"
}
}
showbtn=()=>{
this.setState({
isshow:!this.state.isshow
})
}
render() {
return (
<div className="App">
{
this.state.isshow?<Life/>:""
}
<button onClick={this.showbtn}>isshow</button>
</div>
);
}
}
export default App;
Life.js组件
import React,{Component} from "react"
class Life extends Component {
constructor(props) {
super(props);
this.state = {
msg:"我是修改之前的值"
};
}
//修改值
setmsg=()=>{
this.setState({
msg:"我是修改之后的值"
})
}
//继承了组件的生命周期----就是方法
//渲染之前
componentWillMount(){
console.log("渲染之前");
}
//渲染完成之后
componentDidMount(){
console.log("渲染之后");
}
// 确认是否修改
shouldComponentUpdate(){
return true
}
//修改之前
componentWillUpdate(){
console.log("修改之前")
}
//修改之后
componentDidUpdate(){
console.log("修改之后")
}
//一个组件要从父组件接收值
//如果这个组件是第一次存在于这个中,不会执行
//如果这个组件之前已经存在父组件中,才会执行
//卸载 生命周期
componentWillUnmount(){
console.log("卸载")
}
//props 的值放生改变的时候调用的
componentWillReceiveProps(){
}
//开始渲染
render() {
console.log("开始渲染")
return (
<div>
Life
<button onClick={this.setmsg}>开始修改值</button>
</div>
);
}
}
export default Life;
生命周期函数的使用场景
1.提升性能,避免组件进行无用的render操作
当父组件内容改变时,避免子组件一直进行无用的render操作
shouldComponentUpdate(nextProps,nextState){
if(nextProps.content!== this.props.content){
return true
}else{
return false
}
}
render() {
const {content}=this.props;
console.log("render")
return (
<div onClick={this.handleClick}>{content}</div>
);
}
2.发送ajax请求,只渲染一次
componentDidMount(){}