react-redux-hook

79 阅读1分钟

通过context来获取store里的三个函数个当做useSelector和useDispatch对应的返回值

api

    const count = useSelector(({count}) => count)
    const dispatch = useDispatch()

    const add = () => {
        dispatch({type:'ADD'})
    }

useSelector

import { useContext } from "react";
import { Context } from "../context";

export default function useSelector(selector) {
  const store = useContext(Context);
  const { getStore } = store;
  const state = selector(getStore());
  return state;
}

useDispatch

import { useContext,useLayoutEffect} from "react";
import { Context } from "../context";
import { useForceUpdate } from "../hook";

export default function useDispatch() {
    const store = useContext(Context)
    const {getState,dispatch,subscribe} = store
    const forceUpdate = useForceUpdate()
    // useLayoutEffect(() => {
    //   const unSubScribe = subscribe(() => {
    //     forceUpdate();
    //   });
    //   return () => {
    //     unSubScribe();
    //   };
    // },[subscribe]);

        /*
    react18写法
    */
    useSyncExternalStore(() =>{
        subscribe(() => {forceUpdate()})
    },getState)
    return dispatch
}