useReducer
useReducer 和 useState 的用法很相似,甚至在 preact 中,两者实现都是一样的。useReducer 接收一个 reducer 函数和初始 state,返回了 state 和 dispatch 函数,常常用于管理一些复杂的状态,适合 action 比较多的场景。
function Counter() {
const [count, dispatch] = useReducer((state, action) => {
switch (action.type) {
case 'increment':
return state + 1;
case 'decrement':
return state - 1;
default:
return state;
}
}, 0);
return (
<div>
<h1>{count}</h1>
<button type="button" onClick={() => dispatch({ type: 'increment' })}>increment</button>
<button type="button" onClick={() => dispatch({ type: 'decrement' })}>decrement</button>
</div>
);
}
useReducer实现原理
let index = 0;
const lastStates = [];
function useReducer(reducer, initialState) {
lastStates[index] = lastStates[index] || initialState;
const current = index;
function dispatch(action) {
lastStates[current] = reducer(lastStates[current], action);
render();
}
index += 1;
return [lastStates[current], dispatch];
}
useReducer
useReducer 和 useState 的用法很相似,甚至在 preact 中,两者实现都是一样的。useReducer 接收一个 reducer 函数和初始 state,返回了 state 和 dispatch 函数,常常用于管理一些复杂的状态,适合 action 比较多的场景。
useReducer实现原理