React Hooks 实现原理笔记
核心原理:闭包存储状态、索引维护次序、变更触发渲染
# useState 模拟实现
const globaltate = []
let hookIndex = 0
function useState(initState) {
const currentIndex = hookIndex++
const state = globaltate[currentIndex] || initState
const setState = (_state) => {
globaltate[currentIndex] = _state
render() // 触发 react 渲染
}
return [state, setState]
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 拓展阅读
编辑 (opens new window)
上次更新: 2024/06/18, 15:36:54