react hooks(二)

从 useContext, useReducer, createContext 到 useCallback, memo, useMemo
import {
  useContext, useReducer, createContext,
  useCallback, memo, useMemo, useState
} from "react";

function reducer(state, action) {
  switch (action.type) {
    case 'add':
      return {
        ...state,
        counter: state.counter + 1
      }
    case 'del':
      return {
        ...state,
        counter: state.counter - 1
      }
    case 'reset':
      return {
        ...state,
        counter: 0
      }
    default:
      return state
  }
}
/**
 * 融合useReducer、createContext
 */
const Store = createContext({});
function Provider(props) {
  const [state, dispatch] = useReducer(reducer, { counter: 0, otherState: "【我是其它的state】" });

  return (
    
      {props.children}
    
  )
}

export default function Parent() {
  return (
    
) } /** * 父组件使用useCallback防止inline函数引起的不必要更新 * useContext获取store */ function Child1() { const { state } = useContext(Store); return (
{">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + state.counter}
) } /** * 父组件使用useCallback防止inline函数引起的不必要更新 * useContext获取dispatch */ const Child2 = function () { const { dispatch } = useContext(Store); const [value, setValue] = useState(""); const functionWidthUseCallback = useCallback(() => dispatch({ type: "add" }), []); const functionWidthOutUseCallback = () => dispatch({ type: "add" }); {/** input输入导入 functionWidthOutUseCallback多次更新*/} return (
setValue(e.target.value)} />
) } function Child3() { const { state } = useContext(Store); const otherState = useMemo(() => { return state.otherState }, []); return (
其它的state{otherState}
) } var Child222 = memo(function (props) { console.log("useCallback>>>>>>>>>>>>>>>>>>" + props.type) return (
Child222
) })

你可能感兴趣的:(react hooks(二))