关于 componentWillReceiveProps 生命钩子

关于 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>


正在回答

登陆购买课程后可参与讨论,去登陆

1回答

同学你好,这样理解是可以的,如下:

只要父组件更新状态时,造成了子组件重新渲染,那么子组件就会执行该生命周期函数:

http://img1.sycdn.imooc.com//climg/60a5f7a70978683a09930428.jpg

祝学习愉快!

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师
插入代码