React那些事

useReducer实现useState

2022-01-11  本文已影响0人  _静夜听雨_

react hooks中用useReducer实现useState原理

function useCustomState(initialState) {

  const reducer = ( state, action) => {
    if (typeof action === 'function') {
      return action(state);
    }
    return action;
  };
  const [state, dispatch] = useReducer(reducer, initialState);

  // setState 和 dispatch 一样引用也不变的
  const setState = useCallback(action => {
    dispatch(action);
  }, []);

  return [state, setState];
}
上一篇 下一篇

猜你喜欢

热点阅读