0
点赞
收藏
分享

微信扫一扫

React的生命周期(16版本的)


在React中,生命周期有4个阶段,每个阶段又由不同的钩子函数组成。

  1. 初始化
  2. 运行中(更新阶段)
  3. 销毁
  4. 错误处理

初始化

在组件初始化阶段就会执行 ,由以下几个钩子函数构成

  1. constructor
  2. static getDerivedStateFromProps()
  3. componentWillMount()/UNSAFE_componentWillMount
  4. render()
  5. componentDidMount()

constructor

在组件挂载之前执行,调用super(props),用来将父组件传来的props绑定到这个类中,使用this.props将会得到。

定义状态:状态初始化也可以有父组件传递过来的属性来进行赋值

constructor (props) {
super(props)
this.state = {
name : props.name
}
console.log('01-constructor')
}

效果:页面一打开就会在控制台打印01-constructor

static getDerivedStateFromProps()

在组件实例化后,和接受新的props后被调用。他必须返回一个对象来更新状态,或者返回null表示新的props不需要任何state的更新。

constructor (props) {
super(props)
this.state = {
//name : props.name
}
console.log('01-constructor')
}

static getDerivedStateFromProps(){ //未来版本的componentWillMount()
console.log('02-static getDerivedStateFromProps')
return null //必须返回一个对象来更新状态,或者返回null表示新的props不需要任何state的更新。
}

效果:页面打开执行一次,改变state或者props执行一次

推演:

  • 可以将父组件传递过来的props来初始化一个state,再在子组件写方法修改state (不推荐)
constructor (props) {
super(props)
this.state = {
name : props.name
}
console.log('01-constructor')
}

changeName=()=>{
this.setState({
name : '妈妈'
})
}
render () {
// let { changeName} = this.props
let { name } = this.state
return (
<Fragment>
<h3>初始化阶段---5个钩子函数</h3>
<button onClick={ this.changeName }>改个称呼</button>
<p>称呼ta为---{ name }</p>
</Fragment>
)
}

props的数据不会更改,state的数据可以修改,视图可以更新

  • 直接从props里取用数据和方法
render () {
let { changeName,name} = this.props
return (
<Fragment>
<h3>初始化阶段---5个钩子函数</h3>
<button onClick={ changeName }>改个称呼</button>
<p>称呼ta为---{ name }</p>

</Fragment>
)
}

props更改了,state不会更改,视图可以更新

static getDerivedStateFromProps()还可以接收两个参数

static getDerivedStateFromProps( nextProps,prevState ){   //未来版本的componentWillMount()
console.log('nextProps',nextProps)
console.log('prevState',prevState)
console.log('02-static getDerivedStateFromProps')
return null
}

控制台输出

//页面一打开
nextProps {name: "爸爸", changeName: ƒ}
index.js:19 prevState {}
index.js:20 02-static getDerivedStateFromProps
//单击按钮修改了props
index.js:18 nextProps {name: "妈妈", changeName: ƒ}
index.js:19 prevState {}
index.js:20 02-static getDerivedStateFromProps

componentWillMount() ---组件即将挂载

注意:

static getDerivedStateFromProps vs componentWillMount他们功能是一致的,但是 前一个是未来版本使用, 后一个 未来版本将会被淘汰,但是现低版本用的都是它

作用:数据请求, 将请求来的数据赋值给当前组件的状态

componentWillMount () {   //在未来版本被淘汰(官方说17版本)
console.log('03-componentWillMount')
}

当我们的实例化中有数据请求部分时,我们需要借助setTimeOut()来处理,将实例化仍在setTimeOut里,目的将其仍在异步队列里,让数据请求优先执行完成,在进行实例化,以swiper的例子来讲,我们让轮播的图片通过数据请求获得

componentDidMount(){
fetch('/data.json') //不是./
.then(res=>res.json())
.then(data=>{
this.setState({
data : data
})

setTimeout(()=>{//仍在异步队列里,就是在数据请求到后再实例化
this.Swiper = new Swiper ('.swiper-container', {

loop: true, // 循环模式选项

// 如果需要分页器
pagination: {
el: '.swiper-pagination',
},

// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},

// 如果需要滚动条
scrollbar: {
el: '.swiper-scrollbar',
},
})
},0)
})
}

render()

当他被调用时,他将计算this.props和this.state,返回一个类型

componentDidMount() ---推荐用来做数据请求

- 组件装载结束,将VDOM 渲染成了真实DOM
- 操作真实DOM( 第三方实例化 )
- 数据请求 ( 阿里用 )
componentDidMount () {
console.log('05-componentDidMount')
}

总结:

  1. static getDerivedStateFromProps 和 render在初始化后还可以根据条件再次出发
  2. static getDerivedStateFromProps vs componentWillMount他们功能是一致的,但是 前一个是未来版本使用, 后一个 未来版本将会被淘汰,但是现低版本用的都是它

运行中(更新阶段)

表示当属性或状态发生更新时的阶段

更新阶段一共有7个钩子

  1. componentWillReceiveProps()/UNSAFE_componentWillReceiveProps()
  2. static getDerivedStateFromProps()
  3. shouldComponentUpdate()
  4. componentWillUpdate()/UNSAFE_componentWillUpdate()
  5. render()
  6. getSnapshotBeforeUpdate()
  7. componentDidUpdate()

componentWillReceiveProps()/UNSAFE_componentWillReceiveProps()

当组件身上属性(props)更改时触发 ,里面有个参数,nextProps

componentWillReceiveProps( nextProps ){
console.log('更新阶段--componentWillReceiveProps')
}
render () {
console.log('04-render')
let { changeName,name} = this.props
let { count } = this.state
return (
<Fragment>
<h3>初始化阶段---5个钩子函数</h3>
<button onClick={ changeName }>改个称呼</button>
<p>称呼ta为---{ name }</p>
<button onClick={ this.changeCount }>改个count</button>
<p>count为:---{ count }</p>

</Fragment>
)
}

单击按钮改个称呼时触发了

static getDerivedStateFromProps()

和初始化阶段的那个一样

shouldComponentUpdate()

决定当props或是state更改时,组件要不要渲染, 默认返回时true

shouldComponentUpdate(){
console.log('更新阶段--shouldComponentUpdate')
return true //为true渲染,false不渲染
}

componentWillUpdate()/UNSAFE_componentWillUpdate

组件即将更新

componentWillUpdate(){
console.log('更新阶段--componentwillUpdate')
}

render() ---同初始化阶段的一样

getSnapshotBeforeUpdate ()

注意:这个组件不可以和componentWillMount,componentWillReceiveProps,componentWillUpdate这三个组件一起用

再这个组件不单独使用,要和componentDidUpdate一起使用

componentDidUpdate()

componentDidUpdate ( prevprops,prevstate,snapshot) {
console.log(prevprops,prevstate,snapshot)
console.log( '更新阶段-componentDidUpdate' )
}

销毁阶段

表示组件被卸载或者删除的阶段 ,可以进清尾工作

一个钩子

componentWillUnmount

componentWillUnmount ()

目的:销毁子组件

子组件:

componentWillUnmount(){
console.log('销毁阶段啦--componentWillUnmount')
}

父组件:

constructor () {
super()
this.state={
name : '爸爸',
flag:true
}
}

destroy=()=>{
this.setState({
flag : false
})
}
render(){
let { name,flag } = this.state
return (
<div className="App">
<button onClick={ this.destroy }>销毁</button>
{ !flag||<Life name={ name } changeName={ this.changeName }></Life> }
</div>
);
}

单击销毁按钮后,子组件Life销毁,执行了子组件的钩子,打印了销毁阶段啦--componentWillUnmount

错误处理

错误处理应用于render()函数内部,指的是render内部发生错误的情况下对该情况进行对应的处理,保证程序还能够运行,而不是直接页面整个崩了

import React from 'react'

class Error extends React.Component {
constructor(props) {
super(props);
this.state = { error: false };
}
componentDidCatch(error, info) {
console.log('错误处理-componentDidCatch')
this.setState({ error, info });
}

errorHandle = () => {
this.setState({
error: true
})
}

render() {
if (this.state.error) {
return (
<div>
<p> 报错了 </p>
{
console.log(new Error("YOLO"))
}
</div>
)
}
return (
<div>
<button onClick = { this.errorHandle }>
抛出错误
</button>
</div>
);
}
}

export default Error




举报

相关推荐

0 条评论