关于 componentWillReceiveProps 生命钩子
老师你好,componentWillReceiveProps 这个生命钩子,我自己试了一下发现:当一个父组件改变自身的数据并且render函数内引用了子组件,但是并没有给子组件传递任何数据,子组件中的 componentWillReceiveProps 函数还是会被执行。也就是说只要父组件中改变了 state 中的值,并且使用了子组件,不管是否给子组件传递这个被改变的数据,这个生命钩子都会被执行的?
父组件
1 | <br><br>import React, { Component } from 'react' ;<br><br>import Child from './child.js' ;<br><br><br><br>class Counter extends Component {<br><br> constructor (props) {<br><br> console.log( 'constructor' );<br><br> super (props);<br><br> this .state = {<br> count: 1<br> };<br> };<br><br><br> clickP = () => {<br> const count = ++ this .state.count;<br><br> this .setState({<br> count<br> });<br> };<br><br><br> UNSAFE_componentWillMount() {<br> console.log( 'UNSAFE_componentWillMount' );<br> };<br><br><br> render () {<br> console.log( 'render' );<br><br> return (<br><br> <div><br> <p onClick={ this .clickP }>希望无论结局如何,都会是 happy ending</p><br><br> <Child /><br><br> </div><br> );<br><br> };<br><br><br> componentDidMount () {<br> console.log( 'componentDidMount' );<br> };<br><br><br> shouldComponentUpdate () {<br> console.log( 'shouldComponentUpdate' );<br> return true ;<br> };<br><br><br> componentWillUpdate () {<br> console.log( 'componentWillUpdate' );<br> };<br><br><br> componentDidUpdate () {<br> console.log( 'componentDidUpdate' );<br> }<br><br><br>};<br><br><br>export default Counter;<br> |
子组件
1 | <br><br>import React, { Component } from 'react' ;<br><br><br>class Child extends Component {<br><br> render () {<br><br> return (<br> <p>1</p><br> );<br><br> };<br><br><br> componentWillReceiveProps () {<br> console.log( 'componentWillReceiveProps ----------' );<br> }<br><br>};<br><br><br>export default Child;<br> |
14
收起
正在回答
1回答
同学你好,这样理解是可以的,如下:
只要父组件更新状态时,造成了子组件重新渲染,那么子组件就会执行该生命周期函数:
祝学习愉快!
4.Vue与React高级框架开发
- 参与学习 人
- 提交作业 239 份
- 解答问题 10739 个
本阶段带你深入前端开发的肌理,通过ES6基础知识和前端主流高级框架的学习,助你快速构建企业级移动webAPP应用,进入职场的终极battle
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧