本文最后更新于 2024-12-16T15:59:57+08:00
# Hooks 与 React
生命周期的关系 #
react Hooks 与 React 生命周期的关系
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import { useState } from "react";
const RenderIndex = () => { const [count, set_count] = useState(0); const handleCount = () => { set_count(count + 1); };
return ( <> <div>{count}</div> <button onClick={() => handleCount()}>点击</button> </> ); };
export default RenderIndex;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import { useEffect, useState } from "react";
const RenderIndex = () => { const [count, set_count] = useState(0); useEffect(() => { console.log("===================================="); console.log("初始化页面"); console.log("===================================="); }, []);
return ( <> <div>{count}</div> <button onClick={() => handleCount()}>点击</button> </> ); };
export default RenderIndex;
|

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import { useEffect, useState } from "react";
const RenderIndex = () => { const [count, set_count] = useState(0); useEffect(() => { console.log("===================================="); console.log("初始化页面"); console.log("===================================="); }, []);
useEffect(() => { console.log("count", count); }, [count]);
const handleCount = () => { set_count(count + 1); }; return ( <> <div>{count}</div> <button onClick={() => handleCount()}>点击</button> </> ); };
export default RenderIndex;
|

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import { useEffect, useRef, useState } from 'react';
const RenderIndex = () => { const [count, set_count] = useState(0);
const domRef = useRef(null);
useEffect(() => { console.log('===================================='); console.log('初始化页面', domRef); console.log('===================================='); }, []);
useEffect(() => { console.log('count', count); }, [count]);
const handleCount = () => { set_count(count + 1); }; return ( <> <div style={{ marginBottom: 20, color: 'pink' }} ref={domRef}> {count} </div> <button onClick={() => handleCount()}>点击</button> </> ); };
export defaul~~t RenderIndex;
|

React的生命周期
https://www.gongyibai.site/React的生命周期/