// 通过数组维护变量
let memoizedState = [];调用hooks生成的值在memoizedState的索引let currentCursor = 0;function useState(initVal) { memoizedState[currentCursor] = memoizedState[currentCursor] || initVal; function setVal(newVal) { memoizedState[currentCursor] = newVal; render(); } // 返回state 然后 currentCursor+1 return [memoizedState[currentCursor++], setVal]; }function useEffect(fn, watch) { const hasWatchChange = memoizedState[currentCursor] ? !watch.every((val, i) => val === memoizedState[currentCursor][i]) : true; if (hasWatchChange) { fn(); memoizedState[currentCursor] = watch; currentCursor++; // 累加 currentCursor }}memoizedState中的数据是按hooks的调用顺序存放的,如果在条件 循环 嵌套函数使用hooks。会导致取值混乱
实现简单useState和useReducer
最新推荐文章于 2024-07-17 17:52:20 发布