useState

const fiber={
stateNode : App,
memoizedState: null,
}

let isMount = true;

function useState(initialState){
let hook;

if(isMount){
hook = {
memoizedState: initialState,
next:null,
queue: {
pending:null
}
}
if(!fiber.memoizedState){
fiber.memoizedState = hook;
}else{
workInProgressHook.next = hook;
}
workInProgressHook = hook;
}else{
hook = workInProgressHook ;
workInProgressHook = workInProgressHook.next;
}

// todo

let baseState = hook.memoizedState;

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.memoizedState = baseState;
return [baseState,dispatchAction.bind(null,hook.queue)]
}

function dispatchAction(queue,action){
debugger
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.memoizedState;
const app = fiber.stateNode();
isMount = false;
return app;
}


function App(){

const [num,updateNum] = useState(0)
const [num1,updateNum1] = useState(0)

console.log('isMount?',isMount);

console.log('num',num);

console.log('num1',num1);

return {
onClick(){
updateNum(num => num + 1);
updateNum(num => num + 1);
},
onFocus(){
updateNum1(num => num + 1);
}
}
}

window.app = schedule();

posted @ 2023-05-10 22:57  果果1024  阅读(46)  评论(0编辑  收藏  举报