react hooks 生命周期

583 阅读1分钟

function Component(props) {

console.log('Body');
const [count, setCount] = useState(0);
const willMount = useRef(true);

  //componentWillMount
if (willMount.current) {
    console.log('First time load (it runs only once)');
    setCount(2);
    willMount.current = false;
} else {
    console.log('Repeated load');
}

//componentDidMount   return->componentWillUnmount
useEffect(() => {
    console.log('Component did mount (it runs only once)');
    return () => console.log('Component will unmount');
}, []);

 //componentDidUpdate
useEffect(() => {
    console.log('Component did update');
});

//componentWillReceiveProps
useEffect(() => {
    console.log('Component will receive props');
}, [count]);


return (
    <>
    <h1>{count}</h1>
    <RenderLog>{count}</RenderLog>
    </>
);

}