简单的 useState 源码
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| let isMount = true
let workInProgressHook = null
const fiber = { stateNode: App, memorizedState: null }
function useState(initialState) { let hook
if (isMount) { hook = { memorizedState: initialState, next: null, queue: { pending: null } } if (!fiber.memorizedState) { fiber.memorizedState = hook workInProgressHook = hook } else { workInProgressHook.next = hook } workInProgressHook = hook } else { hook = workInProgressHook workInProgressHook = workInProgressHook.next } let baseState = hook.memorizedState
if (hook.queue.pending) { let firstUpdate = hook.queue.pending.next
do { const action = firstUpdate.action baseState = action(baseState) firstUpdate = firstUpdate.next } while (firstUpdate !== hook.queue.pending.next)
hook.queue.pending = null }
hook.memorizedState = baseState return [baseState, dispatchAction.bind(null, hook.queue)] }
function dispatchAction(queue, action) { const update = { action, next: null }
if (queue.pending === null) { update.next = update } else { update.next = queue.pending.next queue.pending.next = update } queue.pending = update
schedule() }
function schedule() { workInProgressHook = fiber.memorizedState fiber.stateNode() isMount = false }
function App() { const [num1, updateNum1] = useState(0) const [num2, updateNum2] = useState(10)
return { onClick() { updateNum1(num => num + 1) updateNum1(num => num + 1) updateNum1(num => num + 1) } }
}
window.app = schedule()
|
为什么组件 render 时,useState 的状态不会被重置?
因为状态是被维护在组件外部的 Fiber 对象中的 memorizedState 这个属性中的,我们在组件内使用的只是对外层对象中属性的引用(闭包)。
参考
https://www.bilibili.com/video/BV1iV411b7L1/?spm_id_from=333.337.search-card.all.click&vd_source=1616b746cefe2e7615c229563ba38eb4