react componentWillReceiveProps

本文详细探讨了React中componentWillReceiveProps生命周期方法的工作原理,指出它可以在接收到新属性时更新组件状态。但需要注意,当传递的是引用类型属性时,即使属性值改变,组件可能不会重新渲染。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

总结:

1.组件初次渲染时不会执行componentWillReceiveProps;

2.当props发生变化时执行componentWillReceiveProps;

3.在这个函数里面,旧的属性仍可以通过this.props来获取;

4.此函数可以作为 react 在 prop 传入之后, render() 渲染之前更新 state 的机会。即可以根据属性的变化,通过调用this.setState()来更新你的组件状态,在该函数中调用 this.setState() 将不会引起第二次渲染。

5.也可在此函数内根据需要调用自己的自定义函数,来对prop的改变做出一些响应。

注意:
当父组件向子组件传递引用类型(或复合类型,比如对象、数组等)的属性时,要注意打印的this.props和nextProps的内容是一致的,因为引用类型在内存中只有一份,传值时是浅拷贝


 

 

import React, {
    Component
} from 'react'
//当组件执行完componentDidMount函数后,就进入了
class ParentBy extends Component {
    constructor() {
        super()
        this.state = {
            count: 4,
        }
    }
    setSave(){
        this.setState({
            count:this.state.count+1,
            

        })
    }
    render() {
        return ( <div> <button onClick = {
            this.setSave.bind(this)
        }>fdjaksfkl</button> parent{this.state.count} <Son value={this.state.count}> </Son></div> )
    }
}
class Son extends Component {
    constructor(prop) {
        super()
        this.state={
            count:prop.value,
            jiuzhi:prop.value
        }
    }
    render() {
        return ( <div> Son jiuzhi {this.state.jiuzhi}xinzhi{this.state.count}fuzhi{this.props.value}</div>)
        }
        componentWillReceiveProps(nextProp){
console.log(this.props.value)
this.setState({
    count:nextProp.value,
    jiuzhi:this.props.value
})
        }
    }
   
    class Count extends Component {
        constructor() {
            super()
            //
            this.state = {
                num: 2
            }
        }
        setSave() {
            this.setState({
                num: this.state.num + 1
            })
        }
        render() {
            return ( <div>
                <div ref = 'countH' onClick = {
                    this.setSave.bind(this)
                } > f附件打开啦JFK拉萨的是 </div>
                当店count++{
                    this.state.num
                } <ParentBy> </ParentBy> </div>
            )
        }
        shouldComponentUpdate(nextProp, nextState) {
            return (this.state.num % 2 == 0) ? true : false
        }
        componentWillUpdate() {
            console.log(this.refs.countH.innerHTML)

        }
    }

    export default class Index extends Component {
        render() {
            return ( <div >
                我是首页 <Count > </Count> </div>
            )
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值