react常用hook详解

react常用hook详解

DansRoh Lv4

useState()

useState用法

用法:传入一个参数作为状态的初始值,返回两个值,第一个是当前状态的熟悉,第二个是修改状态的方法

const [value, setValue] = useState(initialValue)

useState实现原理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let memoizedStates = []	
let index = 0
function useState (initialState) {
memoizedStates[index] = memoizedStates[index] || initialState
let currentIndex = index
function setState (newState) {
memoizedStates[currentIndex] = newState
render()
}
return [memoizedStates[index++], setState]
}

function render() {
index = 0
ReactDOM.render(<Counter />, document.getElementById('root'));
}

useEffect()

useEffect用法

useEffect() 接受两个参数,第一个为执行函数,第二个为依赖项数组

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
/*
useEffect的用法一般分为四种情况
*/
const [value, setValue] = useState(initialValue)
// 1.不传递依赖项数组
useEffect(()=>{
//code1
})
// 每次render都会执行code1

// 2.传入一个空数组
useEffect(()=>{
//code1
},[])
// 只在挂载和卸载的时候执行code1

// 3.传入依赖项
useEffect(()=>{
// code1
},[value])
// 只在依赖项value发生改变时执行code1

// 4.传入的函数使用return
useEffect(()=>{
// code1
return ()=>{
//code2
}
},[value])
// useEffect方法的第一个参数是一个函数,函数可以return一个方法
// 这个方法就是在组件销毁的时候会被调用

useRef()

useRef 返回一个可变的 ref 对象,其 .current 属性被初始化为传入的参数(initialValue)。返回的 ref 对象在组件的整个生命周期内保持不变。

  1. 获取真实DOM
  2. 记录组件更新之前的值
1
2
3
4
5
6
7
8
9
10
11
12
13
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` 指向已挂载到 DOM 上的文本输入元素
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
  • 标题: react常用hook详解
  • 作者: DansRoh
  • 创建于 : 2022-04-19 00:00:00
  • 更新于 : 2024-06-24 17:16:59
  • 链接: https://blog.shinri.me/2022/04/19/09_react常用hook详解/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论