Mini实现
当做启发,不是真实内部实现
1import React, { useState } from "react";2import ReactDOM from "react-dom";34function CounterEffect() {5 effectCursor = 0; // 注意将 effectCursor 重置为067 const [count, setCount] = useState(0);8 const [count1, setCount1] = useState(0);910 useEffect(() => {11 console.log(count);12 }, [count]);1314 useEffect(() => {15 console.log(count1 + "哈哈哈");16 }, [count1]);1718 const onClick = () => {19 setCount(count + 1);20 };2122 const onClick1 = () => {23 setCount1(count1 + 1);24 };2526 return (27 <div>28 <div>{count}</div>29 <button onClick={onClick}>点击</button>30 <div>{count1}</div>31 <button onClick={onClick1}>点击</button>32 </div>33 );34}3536const allDeps: Array<any[] | undefined> = [];37let effectCursor: number = 0;3839function useEffect(callback: () => void, depArray?: any[]) {40 if (!depArray) {41 callback();42 allDeps[effectCursor] = depArray;43 effectCursor++;44 return;45 }46 const deps = allDeps[effectCursor];47 const hasChangedDeps = deps48 ? depArray.some((el, i) => el !== deps[i])49 : true;50 if (hasChangedDeps) {51 callback();52 allDeps[effectCursor] = depArray;53 }54 effectCursor++;55}5657export function render() {58 ReactDOM.render(59 <React.StrictMode>60 <CounterEffect />61 </React.StrictMode>,62 document.getElementById("root")63 );64}