使用react的Hook写个redux

redux

import * as React from 'react'
const { useContext, useReducer, createContext } = React
//核心-->一定要返回状态
function reducerInAction(state, action) {
    if (typeof action.reducer == 'function') {
        return action.reducer(state)
    }
    return state
}
//公用的数据处理
export default function createStore(params) {
    const { initialState = {}, reducer
    } = {
        ...params,
        reducer: reducerInAction
    }
    //实际是由createContext所有状态版本的管理
    const Appcontext = createContext()
    const middleWareReducer = (lastState, action) => {
        //更新数据
        let netxState = reducer(lastState, action)
        store._state = netxState
        return netxState
    }
    const store = {
        _state: initialState,
        dispatch: undefined,
        getState: () => {
            return store._state
        },
        useContext: () => {
            return useContext(Appcontext)
        }
    }
    //数据包裹返回
    const Provider = props => {
        const [state, dispatch] = useReducer(middleWareReducer, initialState)
        if (!store.dispatch) {
            store.dispatch = async (action) => {
                if (typeof action === 'function') {
                    await action(dispatch, store.getState())
                } else {
                    dispatch(action)
                }

            }
        }
        return 
    }

    return {
        Provider,
        store
    }
}

调用代码

import * as React from 'react'
import HooksRedux from './HooksRedux'
const {
    Provider,
    store
} = HooksRedux({
    initialState: { name: '微微', age: 0 }
})
const Home = () => {
    const state = store.useContext()
    return (
        < div >
            Home组件Age: {state.age}
            
) } //同步请求 const actionOfAdd = () => { return { type: 'addCount', reducer(state) { return { ...state, age: state.age + 1 } } } } function timeOutAdd(a) { return new Promise(cb => setTimeout(() => cb(a - 1), 500)) } //异步请求 const actionAsyncOfDelete = () => async (dispatch, ownState) => { const age = await timeOutAdd(ownState.age) dispatch({ type: 'addCount', reducer(state) { return { ...state, age } } }) } //出发请求 const Button = () => { function handleAdd() { //返回给dispacth的是一个对象 store.dispatch(actionOfAdd()) } function handleAsyncDelete() { //返回给dispacth的是一个对象 store.dispatch(actionAsyncOfDelete()) } return <> } const WarpHome = () => { return ( ) } export default WarpHome

 

你可能感兴趣的:(react学习,react,hook,redux)