目前正在学习深入浅出React【真正吃透React知识链路与底层逻辑】共23讲_哔哩哔哩_bilibili
React组件生命周期
Questions:
- reactDOM.render是如何运作的
- updating的时候还是由reactDOM.render来承接渲染工作的吗
- componentWillUpdate在什么时候会用,16以后需要用怎么样的getDerivedStateFromProps和componentDidUpdate组合才能实现一样的效果呢
- getDerivedStateFromProps执行之后会更新state。这个state的变化是等价于setState的么
React15 vs React16.3 vs React16.4
最大的变化
componentWillMount, componentWillReceiveProps, componentWillUpdate 被删除了。他们被移除主要是为了fiber框架铺路,React15里面的所有步骤都是同步的,但是这样会导致每一次更新视图都需要抢走一整块处理器。React16里面将render及之前的步骤都可以异步执行,也就是可以打断和重复执行。这意味着在render之前的步骤最好只执行一次,如果执行多次,最好也不要对这个compoennt的state产生影响。
React15
- Mounting, 初始化只会运行一次
图片从视频里面节选
- constructor(props), 一般用来做state的初始化
- componentWillMount(), 很多余,这一步可以完全被constructor取代
- render(), 得到虚拟DOM,获得需要渲染的内容
- reactDOM.render,将虚拟DOM转换为DOM?
- componentDidMount(), 一般用来做async请求(如数据的获取),常常会伴随this.setState。还可以用来对DOM进行操作,因为在这一阶段真实的DOM已经被生成
- Updating
图片从视频里面节选
- componentWillReceiveProps(nextProps), 在父组件有任何更新的时候这个方法都会被触发, 但是并不会由组件本身的state更新来触发
- shouldComponentUpdate(nextProps, nextState), 判断组件是否应该更新
- componentWillUpdate,?
- render
- 实际DOM更新,是由谁来完成的?还是reactDOM.render吗
- componentDidUpdate,这个阶段常用来通知父组件我已经渲染好了
- UnMounting
- 触发原因:
- 组件在父组件中被移除
- 父组件的key发生了变化
- componentWillUnmount
- 触发原因:
React 16.3 and React 16.4
16.3:
16.4:
- Mounting
- constructor(props)
- static getDerivedStateFromProps(props, state): {} | null, 并不是为了取代componentWillUpdate,主要目的是为了从props派生state。需要返回值,然后定向更新state,只会更新返回object里面有的key
- render
- update DOM and refs
- componentDidMount()
- Updating
- new props(parent更新), state变化,forceUpdate
- static getDerivedStateFromProps:
- 16.3: 只有new props会触发这个method
- >16.3: 所有的updating都会触发这个method
- should component update
- 除了forceUpdate都会触发这个method
- render
- getSnapShotBeforeUpdate(prevProps, prevState), 返回的值将会传入componentDidUpdate(prevProps, prevState, snapshot)里面作为第三个参数。这个方法最常用的是需要之前的DOM信息,因为componentDidUpdate被运行的时候DOM已经被更新了
- update DOM and refs
- componentDidUpdate(prevProps, prevState, snapshot)
- unmounting
- componentWillUnmount