原理
import React from 'react';
import ReactDOM from 'react-dom';
interface WorkHook {
memoriedState: any,
next: WorkHook | undefined
}
let firstWorkHook: WorkHook = {
memoriedState: undefined,
next: undefined
};
let currentWorkHook = firstWorkHook;
function useReducer(reducer: Function, initArg: any, init?: Function) {
let current: WorkHook = currentWorkHook;
if (typeof current.memoriedState === 'undefined') {
let initState = initArg;
if (typeof init === 'function') {
initState = init(initArg);
}
current.memoriedState = initState;
}
current.next = currentWorkHook = current.next ? current.next : { memoriedState: undefined, next: undefined };
let dispatch = (action: any) => {
current.memoriedState = reducer(current.memoriedState, action);
render();
}
return [
current.memoriedState,
dispatch
]
}
function useEffect(callback: Function, dependencies?: any[]) {
if (typeof dependencies === 'undefined') {
return callback();
}
let current = currentWorkHook;
let memoriedDependencies = current.memoriedState;
if (typeof memoriedDependencies === 'undefined') {
current.memoriedState = dependencies;
callback();
} else {
if (!dependencies.every((item, index) => item === memoriedDependencies[index])) {
callback();
current.memoriedState = dependencies;
}
}
current.next = currentWorkHook = current.next ? current.next : { memoriedState: undefined, next: undefined };
}
function useState(initialState: any) {
return useReducer((state: any, action: any) => action, initialState);
}
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
let reducer = (number: any, action: any) => {
switch (action.type) {
case INCREMENT:
return number + 1;
case DECREMENT:
return number - 1;
default:
return number;
}
}
let init = (number: number) => {
return number;
}
let Counter = () => {
let [number, dispatch] = useReducer(reducer, 0, init);
let [name, setName] = useState('计数器');
useEffect(() => {
alert('名字改变了');
}, [name]);
useEffect(() => {
alert('数值改变了');
}, [number]);
useEffect(() => {
alert('只出现一次');
}, []);
useEffect(() => {
alert('每次都有我');
});
return <>
<p>{name}:{number}</p>
<button onClick={() => dispatch({ type: INCREMENT })}>+</button>
<button onClick={() => dispatch({ type: DECREMENT })}>-</button>
<button onClick={() => setName('计数器' + Date.now())}>改名字</button>
</>
}
function render() {
currentWorkHook = firstWorkHook;
ReactDOM.render(<Counter />, document.getElementById('root'));
}
render();
结果