From d436e1cff0b2c21998d72a1e5245b43281c0aa40 Mon Sep 17 00:00:00 2001 From: marklin2012 Date: Tue, 17 Dec 2019 15:16:49 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20hooks=20=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/index.js | 4 +++- src/yolkjs/index.js | 31 +++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index 6a1f15c..0654b51 100644 --- a/src/index.js +++ b/src/index.js @@ -6,11 +6,13 @@ import React from './yolkjs' const ReactDOM = React function App(props) { + const [count, setCount] = React.useState(1) return (

hello, {props.title}

-

react dom

+

react dom {count}

shop +
) } diff --git a/src/yolkjs/index.js b/src/yolkjs/index.js index d97bdf1..9f1a84c 100644 --- a/src/yolkjs/index.js +++ b/src/yolkjs/index.js @@ -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) } @@ -268,4 +298,5 @@ requestIdleCallback(workLoop) export default { createElement, render, + useState, } \ No newline at end of file