9. 生命周期
This commit is contained in:
parent
6560620061
commit
ec0298cf63
@ -16,6 +16,17 @@ export default class SonComponent extends React.PureComponent {
|
||||
|
||||
componentDidMount() {
|
||||
this.changeChildrenClass()
|
||||
console.log('[挂载] SonComponent 组件后执行的操作');
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps, prevState, snapshot) {
|
||||
// 当count更新时执行的操作
|
||||
console.log('SonComponent 组件后更新,执行的操作:', this.state);
|
||||
}
|
||||
|
||||
|
||||
componentWillUnmount() {
|
||||
console.log('[卸载] SonComponent 组件 前执行的操作');
|
||||
}
|
||||
|
||||
switchChildrenBorder = () => {
|
||||
@ -68,7 +79,7 @@ export default class SonComponent extends React.PureComponent {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<button onClick={this.switchChildrenBorder}>切换边框显示</button>
|
||||
<button onClick={this.switchChildrenBorder}>切换边框显示</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -3,12 +3,29 @@ export default function SonComponent2(props= {
|
||||
msg:"",
|
||||
changeMsg:(_)=>{}
|
||||
}){
|
||||
|
||||
// 模拟 componentDidMount
|
||||
useEffect(() => {
|
||||
// 在组件挂载后执行的操作
|
||||
console.log('[挂载] SonComponent2 组件后执行的操作');
|
||||
return () => {
|
||||
// 在组件卸载前执行的操作
|
||||
console.log('[卸载] SonComponent2 组件 前执行的操作');
|
||||
};
|
||||
}, []); // 空数组意味着仅在组件挂载时执行一次
|
||||
|
||||
const [state, setState] = useState({
|
||||
msg: "son msg",
|
||||
tmp: "",
|
||||
count: 0,
|
||||
})
|
||||
|
||||
// 模拟 componentDidUpdate
|
||||
useEffect(() => {
|
||||
// 当count更新时执行的操作
|
||||
console.log('SonComponent2 组件后更新,执行的操作:', state);
|
||||
}, [state]); // 依赖于 state,当 state 变化时执行
|
||||
|
||||
function changeMsg(){
|
||||
let target = `parent msg 被修改 (${++state.count})`
|
||||
setState({
|
||||
|
Loading…
Reference in New Issue
Block a user