面试题答案
一键面试以下以React为例:
import React, { Component } from 'react';
class Child extends Component {
componentDidUpdate(prevProps) {
if (prevProps.count!== this.props.count) {
console.log(`count值从 ${prevProps.count} 变为 ${this.props.count}`);
}
}
render() {
return <div>子组件接收的count: {this.props.count}</div>;
}
}
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
setTimeout(() => {
this.setState({ count: this.state.count + 1 });
}, 2000);
}
render() {
return (
<div>
<Child count={this.state.count} />
</div>
);
}
}
export default Parent;
上述代码实现了父组件Parent
将状态count
传递给子组件Child
,并在子组件Child
的componentDidUpdate
生命周期中,当count
变化时在控制台打印信息。父组件在挂载后两秒更新count
值,触发子组件的componentDidUpdate
。