React的生命周期

# Hooks 与 React 生命周期的关系 # react Hooks 与 React 生命周期的关系

  • useState:定义并初始化数据
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;
  • useEffect:初始化页面 & 监听数据
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;

  • useRef:获取 dom 节点
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);

// 获取真实dom节点
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的生命周期/
作者
爱吃糖醋排骨的苏小妍.
发布于
2024-11-27 10:37:21
更新于
2024-12-16 15:59:57
许可协议