这一小节我们来优化一下useState的实现方式。真正react中实现并不是我们在调用setCount的时候就更新,而是会把每次的变化存起来,在某一个时机进行批量处理。
function useState(initial) {
let currentFiber = wipFiber;
const oldHook = currentFiber.alternate?.stateHooks[stateHookIndex]
const stateHook = {
state: oldHook ? oldHook.state : initial,
queue: oldHook ? oldHook.queue : []
}
stateHook.queue.forEach(action => {
stateHook.state = action(stateHook.state)
})
stateHook.queue = []
stateHookIndex++
stateHooks.push(stateHook)
currentFiber.stateHooks = stateHooks
function setState(action) {
stateHook.queue.push(action)
wipRoot = {
...currentFiber,
alternate: currentFiber
}
nextWorkOfUnit = wipRoot
}
return [stateHook.state, setState]
}
支持直接输入非function的值
function useState(initial) {
// ...
function setState(action) {
const newAction = typeof action === 'function' ? action : () => action
stateHook.queue.push(newAction)
wipRoot = {
...currentFiber,
alternate: currentFiber
}
nextWorkOfUnit = wipRoot
}
return [stateHook.state, setState]
}