关于 componentWillReceiveProps 生命钩子
来源:2-11 React 中的生命周期函数(4)
粉墨登场
2021-05-20 11:10:03
老师你好,componentWillReceiveProps 这个生命钩子,我自己试了一下发现:当一个父组件改变自身的数据并且render函数内引用了子组件,但是并没有给子组件传递任何数据,子组件中的 componentWillReceiveProps 函数还是会被执行。也就是说只要父组件中改变了 state 中的值,并且使用了子组件,不管是否给子组件传递这个被改变的数据,这个生命钩子都会被执行的?
父组件
import React, { Component } from 'react';
import Child from './child.js';
class Counter extends Component {
constructor (props) {
console.log('constructor');
super(props);
this.state = {
count: 1
};
};
clickP = () => {
const count = ++this.state.count;
this.setState({
count
});
};
UNSAFE_componentWillMount() {
console.log('UNSAFE_componentWillMount');
};
render () {
console.log('render');
return (
<div>
<p onClick={ this.clickP }>希望无论结局如何,都会是 happy ending</p>
<Child />
</div>
);
};
componentDidMount () {
console.log('componentDidMount');
};
shouldComponentUpdate () {
console.log('shouldComponentUpdate');
return true;
};
componentWillUpdate () {
console.log('componentWillUpdate');
};
componentDidUpdate () {
console.log('componentDidUpdate');
}
};
export default Counter;
子组件
import React, { Component } from 'react';
class Child extends Component {
render () {
return (
<p>1</p>
);
};
componentWillReceiveProps () {
console.log('componentWillReceiveProps ----------');
}
};
export default Child;
1回答
同学你好,这样理解是可以的,如下:
只要父组件更新状态时,造成了子组件重新渲染,那么子组件就会执行该生命周期函数:
祝学习愉快!
相似问题
回答 1
回答 1