import * as React from 'react';
import { connect as reduxConnect } from 'react-redux';
import {
createStore,
combineReducers,
bindActionCreators,
applyMiddleware
} from 'redux';
import { connectRouter, routerMiddleware } from 'connected-react-router';
import { createBrowserHistory } from 'history';
import ThunkMiddleware from 'redux-thunk';
import hoistNonReactStatic from 'hoist-non-react-statics';
import {
reducer as homeModal,
InitialState as homeModalInitialState,
actions as homeModalactions
} from '../src/modal/home';
export const history = createBrowserHistory()
const createRootReducer = (history: any) =>
combineReducers({
homeModal,
router: connectRouter(history)
})
export interface IState {
homeModal: homeModalInitialState
}
// Strong type connect
type IMapStateToProps = (state?: IState, props?: any) => object;
export const actions = {
homeModal: homeModalactions
}
export type IActions = typeof actions;
function createActions(dispatch: any) {
return {
homeModal: bindActionCreators(homeModalactions, dispatch)
}
}
interface HOC {
<T>(arg: T): T
}
export function connect<MapState extends IMapStateToProps>(
mapStateToProps?: MapState
): <Props = {}>(
reactComponent: React.FC<ReturnType<MapState> & Props & IActions>
) => React.FunctionComponent<Props & any> {
const hoc: HOC = (Comp: any) => {
const ConnectComp = reduxConnect(mapStateToProps, (dispatch: any) =>
createActions(dispatch)
)((compProps: any) => {
const { forwardRef, ...otherProps } = compProps
return <Comp {...otherProps} ref={forwardRef} />
})
const NewComp: typeof Comp = React.forwardRef((props, ref) => (
<ConnectComp {...props} forwardRef={ref} />
))
hoistNonReactStatic(NewComp, Comp)
return NewComp
}
return hoc
}
export function connectClass<T, MapState extends IMapStateToProps>(
mapStateToProps?: MapState
): (reactClass: React.ComponentClass<any, any>) => any {
const hoc: HOC = (Comp: any) => {
const ConnectComp = reduxConnect(mapStateToProps, (dispatch: any) =>
createActions(dispatch)
)((compProps: any) => {
const { forwardRef, ...otherProps } = compProps
return <Comp {...otherProps} ref={forwardRef} />
})
const NewComp: typeof Comp = React.forwardRef((props, ref) => (
<ConnectComp {...props} forwardRef={ref} />
))
hoistNonReactStatic(NewComp, Comp)
return NewComp
}
return hoc
}
// 注册 fetch middleware
const registerFetchMiddleware = applyMiddleware(
routerMiddleware(history),
ThunkMiddleware,
)
export const store = createStore(createRootReducer(history), registerFetchMiddleware)
typescript 封装Redux store代码实现
于 2022-04-11 14:21:35 首次发布