我们可以用useEffect Hook定义生命周期函数:
import React, { useState, useEffect } from 'react';
function LifecycleDemo() {
const [count, setCount] = useState(0);
useEffect(() => {
// 1.componentDidMount(组件挂载时执行)
console.log('componentDidMount');
// 3.componentWillUnmount (组件卸载时执行)
return () => {
console.log('componentWillUnmount');
};
}, []);
// 2.componentDidUpdate(组件渲染完成时执行)
useEffect(() => {
console.log('componentDidUpdate (without dependencies)');
});
// 2.componentDidUpdate (with count dependency)(count状态更新时候执行)
useEffect(() => {
console.log('componentDidUpdate (with count dependency)');
}, [count]);
return (
<div>
<h1>Lifecycle Demo</h1>
<p>Count: {count}</p>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
<button onClick={() => setCount(c => c - 1)}>Decrement</button>
</div>
);
}
export default LifecycleDemo;
请问下,不再useEffect里面时候是属于哪个生命周期呢?
比如:
const [count, setCount] = useState(0);
是属于哪个生命周期?
属于 render 。
类式组件是
Every thing in Schedule
;函数组件是
Schedule in render function
。你不可能在别的地方找到这两句话,因为都是我刚编的。