一、redux之自定义createStore
export function createStore ( reducer ) {
let state = reducer ( undefined , { type: "redux/init@@" } )
function getState ( ) {
return state
}
function dispatch ( action ) {
state = reducer ( state, action)
listeners. forEach ( listener => listener ( ) )
}
let listeners = [ ]
function subscribe ( listener ) {
listeners. push ( listener)
}
return { getState, dispatch, subscribe }
}
二、redux之自定义combineReducers
export function combineReducers ( reducers ) {
return ( state = { } , action ) => {
return Object. keys ( reducers) . reduce ( ( pre, key ) => {
pre[ key] = reducers[ key] ( state[ key] , action)
return pre
} , { } )
}
}
三、react-redux自定义
import React, { Component } from "react"
import PropTypes from 'prop-types'
const StoreContext = React. createContext ( )
export class Provider extends Component {
static propTypes = {
store: PropTypes. object. isRequired
}
render ( ) {
return (
< StoreContext. Provider value= { this . props. store} >
{ this . props. children}
< / StoreContext. Provider>
)
}
}
export function connect ( mapStateToProps, mapDispatchToProps ) {
return ( UIComponent ) => {
return class ContainerComponent extends Component {
static contextType = StoreContext;
constructor ( props, context ) {
super ( props)
const { getState, dispatch, subscribe } = context
const stateProps = mapStateToProps ( getState ( ) )
this . state = { ... stateProps }
if ( typeof mapDispatchToProps === 'function' ) {
this . dispatchProps = mapDispatchToProps ( dispatch)
} else {
this . dispatchProps = Object. keys ( mapDispatchToProps) . reduce ( ( pre, key ) => {
pre[ key] = ( ... args) => dispatch ( mapDispatchToProps[ key] ( ... args) )
return pre
} , { } )
}
subscribe ( ( ) => {
const stateProps = mapStateToProps ( getState ( ) )
this . setState ( { ... stateProps } )
} )
}
render ( ) {
return < UIComponent { ... this . state} { ... this . dispatchProps} / >
}
}
}
}