Redux类适用所有React生态项目

import {
    applyMiddleware,
    combineReducers,
    legacy_createStore as createStore,
    Store,
    compose,
} from "redux";
import thunk from "redux-thunk";
import {connect, Provider} from "react-redux";
import {Action as ReduxAction, AnyAction} from "redux";

type StoreState = {
    [key: string]: string | number | boolean | undefined | null | unknown | void
}

type StoreMap<T = any, S = any> = {
    namespace: string;
    state: S | StoreState;
    reducers?: {
        [key: string]: (state: StoreState, params: T) => StoreState
    },
    [key: string]: any;
}

interface StoreStore<T = any> {
    namespace: string;
    state: T | StoreState;
    
    [key: string]: any;
}


type StoreStores<T = any> = {
    [key: string]: StoreStore<T>;
};

type StoreReducers<T = any> = {
    [key: string]: T
}

interface Dispatch<A extends ReduxAction = AnyAction> {
    <T extends A> (action: T): T
}

type Params = { [key: string]: any }

export default class Redux<T = Params> {
    public static _collection: Params = {};
    public dispatch: Dispatch;
    public namespace: string;
    public state: T = {} as T;
    
    constructor () {
    
    }
    
    // 所有状态的集合
    public get collection () {
        return Redux._collection;
    };
    
    // 初始化的状态
    public get store () {
        return {
            namespace: this.namespace,
            state: this.state,
        } as {
            namespace: string;
            state: T
        };
    }
    
    // dispatch
    public get action () {
        return (dispatch: Dispatch) => this._renderRedux(dispatch);
    }
    
    // 状态改变
    public setState = (state: T, cb?: (newState: T) => void): T => {
        this.dispatch({
            type: `${this.namespace}/setState`,
            state
        });
        const newState = {
            ...this.state,
            ...state
        };
        this.state = newState;
        if (cb) {
            cb(newState);
        }
        Redux._collection[this.namespace] = newState;
        return newState;
    };
    
    // 创建多个状态
    public createStores (
        stores: StoreStores
    ): Store {
        return createStore(
            combineReducers(
                this._createReducers(
                    {
                        ...stores
                    }
                )
            ), compose(applyMiddleware(thunk)
            )
        );
    }
    
    // 根据每个store创建xxx/setState
    private _createState (map: StoreMap) {
        const newMap = {...map};
        newMap.reducers = newMap.reducers ? newMap.reducers : {};
        const newReducers: StoreReducers = {};
        newReducers[`${newMap["namespace"]}/setState`] = (_state: StoreState, {state}: { state: StoreState }) => ({..._state, ...state});
        newMap.reducers = newReducers;
        return (state = newMap.state, action: { type: string }) => {
            if (newMap.reducers && newMap.reducers[action.type]) {
                return newMap.reducers[action.type](state, action);
            } else {
                return state;
            }
        };
    };
    
    private _createReducers (reducers: StoreStores): StoreReducers {
        return Object.entries(reducers).reduce((preItems, item) => {
            const namespace = item[1].namespace;
            Redux._collection[namespace] = item[1].state;
            return {
                ...preItems,
                [namespace]: this._createState(item[1])
            };
        }, {});
    };
    
    private _renderRedux = (dispatch: Dispatch) => {
        this.dispatch = dispatch;
        return this;
    };
}

export {
    Dispatch,
    StoreMap,
    StoreReducers,
    StoreState,
    StoreStores,
    StoreStore,
    Redux,
    connect,
    Provider,
};

继承Redux

import Redux from "@/common/redux/redux";
import {homeAction, HomeAction} from "@/common/redux/home";


interface State {
    desc?: string;
    title?: string;
}
// 继承Redux
export class CommonAction extends Redux<State> {
    private _homeAction: HomeAction;
    
    constructor () {
        super();
        // 这个状态的名字(必须要有)
        this.namespace = 'common';
        // 需要管理的单个状态(必须要有)
        this.state = {
            a: '',
            b: '',
        }
    }
    // home类里的方法在这里调用
    private get $homeAction () {
        if (this._homeAction) {
            return this._homeAction;
        }
        this._homeAction = homeAction(this.dispatch);
        return this._homeAction;
    }    
    
    public onChange = async () => {
        // 所有状态的数据 this.collection['common'] = this.state
        this.collection;
        // 当前common状态
        this.state;
        // 修改common状态
        this.setState({ a: 1, b: 2 });
        // 修改其他状态(这里是home状态)
        this.dispatch({type: 'home/setState', {c: 3, d: 4}})
    };

   public onChangeHome = () => {
       // 调用home里的方法
       this.$homeAction.xxxx();
   } 
}

const common = new CommonAction();

export const commonAction = common.action;
export const commonStore = common.store;

把数据放到全局(可以放多个Store)

import React from "react";
import Taro from "@tarojs/taro";
import Redux, {Provider} from "@/common/redux/redux";
// 各个状态
import {commonStore} from "@/common/redux/common";
import {homeStore} from "@/common/redux/home";



const createStoreChildren = (children) => {
    // 状态各个注册
    const stores = React.useRef(new Redux().createStores({
        commonStore,
        homeStore
    })).current;
    return <Provider store={stores}>
        {children}
    </Provider>;
};

// createStoreChildren用来包裹最外层
export default createStoreChildren;

单个页面或者组件引入使用

...
export default connect((e: {}) => {
    // 把当前页面或者组件导入用到的状态值
    return {
        a: e['common'].a,
        b: e['common'].b,
        c: e['home'].c,
        d: e['home'].d,
    };
}, (dispatch) => {
    // 把当前页面或者组件导入用到的方法
    const home = homeAction(dispatch);
    const common = commonAction(dispatch);
    return {
        dispatch,
        setHomeState: home.setState,
        homeInit: home.homeInit,
        setCommonState: common.setState,
        onChange: common.onChange,
        
    };
})(Index);

perkz
51 声望28 粉丝