总结:
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>
)
}
}