前端开发那些事儿

React-Redux(二):仿照react-redux思路

2021-01-08  本文已影响0人  Viewwei
import {createStore, combineReducers} from "redux";

// 定义修改规则
 const countReducer = (state = 0, action) => {
  switch (action.type) {
    case "ADD":
      return state + 111;
    case "MINUS":
      return state - 1;
    default:
      return state;
  }
};

const store = createStore(combineReducers({count: countReducer}));

export default store;
  1. 创建provide和Context
//实现react-redux工作方式
import React from 'react';
                    
const Context = React.createContext(); 
const Provide = ({children,store}) =>{
    return <Context.Provider value={store}>
        {children}
    </Context.Provider>
}
export {Provide,Context}
  1. 创建useStore
import React,{useContext, useLayoutEffect, useState,useCallback}from 'react';
import {Context} from './reactRedux'
function  useForceUpdate() {
    const[,setState] = useState(0)
    const update = useCallback(() =>{
        setState(pre=>pre+1)
    },[])
    return update
}
export function useStore () {
    const store = useContext(Context) ;//得到store,
    const forceUpdate  = useForceUpdate() //hook 刷新
    useLayoutEffect(()=>{
        const unsubscribe =store.subscribe(() =>{
            forceUpdate() 
        })
        return () =>{
            if (unsubscribe){
                unsubscribe()
            }
        }
    },[store])
    return store
}
  1. 创建useSelector.js文件
import {useStore} from './useStore'
let useSelector = (select) =>{
    const store = useStore()
    const {getState} = store
    const selectState = select(getState()) //等于执行getState() ,拿到state,因为select为函数,所以state就就是参数
    return selectState
}
export {useSelector}

5.创建useDispatch.js文件

import {} from './store'
import { useStore } from './useStore'
let useDispatch = () =>{
    const store = useStore()
    return store.dispatch
}
export {useDispatch}

使用就是和正常的react-redux一样

上一篇下一篇

猜你喜欢

热点阅读