Skip to content

Commit

Permalink
feat: hooks 支持
Browse files Browse the repository at this point in the history
  • Loading branch information
marklin2012 committed Dec 17, 2019
1 parent f7aa016 commit d436e1c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ import React from './yolkjs'
const ReactDOM = React

function App(props) {
const [count, setCount] = React.useState(1)
return (
<div id="app">
<h1>hello, {props.title}</h1>
<p>react dom</p>
<p>react dom {count}</p>
<a href="https://jd.com">shop</a>
<button onClick={() => setCount(count + 1)}>add</button>
</div>
)
}
Expand Down
31 changes: 31 additions & 0 deletions src/yolkjs/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,37 @@ function performUnitOfWork(fiber) {
}
}

let wipFiber = null
let hookIndex = null
function useState(init) {
const oldHook = wipFiber.base && wipFiber.base.hooks[hookIndex]
const hook = {
state: oldHook ? oldHook.state : init,
queue: []
}
const actions = oldHook ? oldHook.queue : []
actions.forEach(action => {
hook.state = action
})
const setState = action => {
hook.queue.push(action)
wipRoot = {
dom: currentRoot.dom,
props: currentRoot.props,
base: currentRoot,
}
nextUnitOfWork = wipRoot
deletions = []
}
wipFiber.hooks.push(hook)
hookIndex++
return [hook.state, setState]
}

function updateFunctionComponent(fiber) {
wipFiber = fiber
hookIndex = 0
wipFiber.hooks = []
const children = [fiber.type(fiber.props)]
reconcileChildren(fiber, children)
}
Expand Down Expand Up @@ -268,4 +298,5 @@ requestIdleCallback(workLoop)
export default {
createElement,
render,
useState,
}

0 comments on commit d436e1c

Please sign in to comment.