Redux 相关原理解析

redux概念

应用的所有状态以一个对象的形式存储在唯一的 store 里面,我们可以把这个存储状态的对象叫状态树,而更改对象树的唯一方式就是 emit 一个 action(这个 action 是一个描述发生了什么的对象),为了把这个 action 转换为对象树里面的某个值,就需要提供一个 reducer, 所以简单来说,一个redux程序包括一个 store、一个 reducer 和多个 action。

简单例子, 也是一个基本使用

import { createStore } from 'redux';

export const reducer = (state = {}, action) => {
    switch (action.type) {
        case 'EXAMPLE_TEST': {
            // balabala
            return {text: 'ready go'}
        }
        default:{
            return state;
        }
    }
};

const initialState = {}; // 初始state
const store = createStore(reducer, initialState);

store.dispatch({type: 'EXAMPLE_TEST', data: {}});
store.subscribe(() => {
   const stateObj = store.getState();
   
   if (stateObj.xxx...) {
     // state树更改了, balabala
   }
})
console.log(store.getState())

上面涉及到的相关 api 逻辑详细解析(node_modules/redux/src..)

createStore

export default function createStore(reducer, preloadedState, enhancer) {
    ...
    
    dispatch({ type: ActionTypes.INIT })
    
    return {
        dispatch,
        subscribe,
        getState,
        replaceReducer,
        [$$observable]: observable
    }
}

从参数可以看出,它是 action 和 reducer 的粘合剂,调用一下 dispatch 生出一个初始化后的对象树(如何生成,见下面的 dispatch 解释),然后向外曝露出一些功能函数,具体功能函数见下面说明。

subscribe
function subscribe(listener) {
    if (typeof listener !== 'function') {
        throw new Error('Expected listener to be a      function.')
    }

    let isSubscribed = true

    ensureCanMutateNextListeners()
    nextListeners.push(listener)

    return function unsubscribe() {
      if (!isSubscribed) {
        return
      }

      isSubscribed = false

      ensureCanMutateNextListeners()
      const index = nextListeners.indexOf(listener)
      nextListeners.splice(index, 1)
    }
  }

把通过 store.subscribe(()=>{}) 添加的 listener 放到 nextListeners 数据里,并返回一个 unsubscribe 函数,用于取消订阅,这里面多次出现的函数:ensureCanMutateNextListeners 作用就是确保 currentListeners 和 nextListeners 不指向同一个数组,把将要执行的 listeners 和以后要执行的 listeners 区分开,这样可以避免掉 listener 正在被执行的时候,突然取消订阅的问题。

getState
function getState() {
    return currentState
}

作用就是返回当前的状态树对象

[$$observable]: observable
function observable() {
    const outerSubscribe = subscribe
    return {
        subscribe(observer) {
            if (typeof observer !== 'object') {
                throw new TypeError('Expected the observer to be an object.')
            }

            function observeState() {
            if (observer.next) {
                observer.next(getState())
            }
        }

        observeState()
        const unsubscribe = outerSubscribe(observeState)
        return { unsubscribe }
      },

      [$$observable]() {
        return this
      }
    }
  }

把 store 针对 state 树变更可 observable,以支持 redux 和 RxJS, XStream and Most.js 等库的联合使用,需要再详细说明的是 $$observable,它来自于 symbol-observable 这个 npm 包,这个包的作用就是使一个对象 observable, 并且避免掉 observable 对象调用完 error, complete 之后重复调用以及 unsubscribe 之后再调用 next, error, complete 函数,具体使用见 README.md:https://github.com/benlesh/sy...

dispatch
function dispatch(action) {
    ...... // 省略掉了非关键代码
    
    try {
        isDispatching = true
        currentState = currentReducer(currentState, action)
    } finally {
        isDispatching = false
    }
    
    const listeners = currentListeners = nextListeners
    for (let i = 0; i < listeners.length; i++) {
        const listener = listeners[i]
        listener()
    }

    return action
  }

dispatch 一个 action,就是把当前 state 对象和 action 传递给传给 store 的 reducer 作为参数,然后 reducer 返回的新对象就是新的 state 树,生成新的 states 树之后,再执行所有通过 store.subscribe 函数注册的 listener, 注册方式见上面 subscribe 说明,最后,我们回到上面 createStore 遗留的 dispatch({ type: ActionTypes.INIT }) 部分,就很明了了,就是生成初始的 state 树。

replaceReducer
function replaceReducer(nextReducer) {
    if (typeof nextReducer !== 'function') {
        throw new Error('Expected the nextReducer to be a function.')
    }

    currentReducer = nextReducer
    dispatch({ type: ActionTypes.INIT })
  }

这个函数主要是替代 creatStore 传进来的 reducer, 使用场景如:代码逻辑里有代码分割逻辑,需要动态加载 reducer; 或者为了实现 redux的热加载, 如:

if (module.hot) {
    module.hot.accept('../reducers', () => {
        const nextRootReducer = require('../reducers').default;
            store.replaceReducer(nextRootReducer);
        });
    }

其中 module.hot 是 webpack 通过 HotModuleReplacementPlugin 开启了模块热替换之后赋予 module 的 hot 属性。

上面说了基本的 redux 使用原理,但是在实际使用中,我们可能会遇到如下问题

  1. 如果项目很复杂,把所有的 action 处理都放到一个 reducer 下,那 reducer 的 case 得写多少,有可能会导致单个文件过大,代码不好维护?
  2. redux 有没有调试工具,以便于我们在开发阶段进行调试,如果有,怎么用?
  3. 项目中每个都少不了网络请求,那么我们每个请求都要判断成功,失败,和请求中三个情况的 dispatch,那么每个请求都这么写,显的累赘, 提取公共部分到公共函数就能解决吗?
  4. redux 应用到项目中,每个组件都要 subscribe 一下,然后判断自己关注的 state 是不是变了吗?

问题一:

redux 提供一个 combineReducers 工具,允许我们写多个小reducer,然后通过 combineReducers 组合成一个 root reducer,也就是一个大 reducer,源码如下:

export default function combineReducers(reducers) {
  const reducerKeys = Object.keys(reducers)
  const finalReducers = {}
  for (let i = 0; i < reducerKeys.length; i++) {
    const key = reducerKeys[i]
    ...
    if (typeof reducers[key] === 'function') {
      finalReducers[key] = reducers[key]
    }
  }
  const finalReducerKeys = Object.keys(finalReducers)
  ...
  return function combination(state = {}, action) {
    ...
    let hasChanged = false
    const nextState = {}
    for (let i = 0; i < finalReducerKeys.length; i++) {
      const key = finalReducerKeys[i]
      const reducer = finalReducers[key]
      const previousStateForKey = state[key]
      const nextStateForKey = reducer(previousStateForKey, action)
      if (typeof nextStateForKey === 'undefined') {
        const errorMessage = getUndefinedStateErrorMessage(key, action)
        throw new Error(errorMessage)
      }
      nextState[key] = nextStateForKey
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey
    }
    return hasChanged ? nextState : state
  }
}

给 combineReducers 传入一个 reducer 对象,然后返回一个 reducer 函数,参数里面每个 value 需要是一个小 reducer 函数, 这些小的 reducer 可以分布到不同的文件里面,那么举一反三,一些最小的 reducer 可以通过 combineReducers 组装成中等的 reducer, 然后这些中等的 reducer 又可以 combineReducers 成最大的 reducer:

export default combineReducers({
    a: combineReducers(...),
    b: combineReducers(...),
    c: combineReducers(...)
});

问题二:

已经有 redux-logger 类似的工具了,我们看它的定义:

// 默认的logger
export const logger: Redux.Middleware;
// 自定义logger
export function createLogger(options?: ReduxLoggerOptions): Redux.Middleware;
// Redux.Middleware
export interface Middleware {
  <S>(api: MiddlewareAPI<S>): (next: Dispatch<S>) => Dispatch<S>;
}

从上面可以看出返回类型都是 Redux.Middleware,这表明它是以 redux 中间件的形式融入到 redux 中, 这些中间件实现方式都是统一的,接收一个 MiddlewareAPI 参数,然后返回一个 function(这个 function 接收一个 dispatch,然后将 dispatch 结果返回)。这些中间件注入到 redux 中需要借助 redux 提供的 applyMiddleware 函数:

export default function applyMiddleware(...middlewares) {
  return (createStore) => (reducer, preloadedState, enhancer) => {
    const store = createStore(reducer, preloadedState, enhancer)
    let dispatch = store.dispatch
    let chain = []

    const middlewareAPI = {
      getState: store.getState,
      dispatch: (action) => dispatch(action)
    }
    chain = middlewares.map(middleware => middleware(middlewareAPI))
    dispatch = compose(...chain)(store.dispatch)

    return {
      ...store,
      dispatch
    }
  }
}

applyMiddleware 接收多个中间件,然后返回一个函数,这个函数参数是一个 createStore, 函数逻辑是调用 createSotre 拿到最基本的 store,然后遍历所有的中间件,给其传入 MiddlewareAPI,拿到中间件执行结果(返回是一个函数,是 Redux.Middleware 类型),然后通过compose把所有中间件给柯里化一下,把基本的 store.dispatch 武装成一个强大的 dispatch,这样每次 dispatch(action) 就会走这些中间件了,也就可以观察 action 结果变化,其中 compose 的函数源代码如下:

export default function compose(...funcs) {
  if (funcs.length === 0) {
    return arg => arg
  }

  if (funcs.length === 1) {
    return funcs[0]
  }

  return funcs.reduce((a, b) => (...args) => a(b(...args)))
}

结合中间件场景:dispatch = compose(...chain)(store.dispatch) 可以理解为以传入的中间件顺序倒序为基准,依次将基础的 store.dispatch 传给各个中间件的返回函数。
综上,中间件落实到项目中使用就是:

import { createStore, applyMiddleware } from 'redux';

const bigCreateStore = applyMiddleware(middleware1, middleware2, ...)(createStore)

bigCreateStore.dispatch(action)

还有很多其他中间件,比如你 action 是个 function 的话就要借助 redux-thunk 中间件。

问题三

我们把它提取到工具类公共函数中,可以是可以,但是整个项目代码看起来不优雅,我们可以向 redux 看齐,以一个中间件的形式落地这个异步请求处理,我们可以自己实现一个中间件,也可以使用现成的, 比如:https://github.com/agraboso/r...

问题四

整个项目中到处充满着 subscribe,而且一旦整个对象树更改了,所有组件的 subscribe 都要执行 state 变化判断,看是否重新 render,这样容易做成无用功,我们可以借助已有的工具:react-redux, 给我们解决掉这个判断处理麻烦,使用事例:

import { Provider, connect } from 'react-redux';

class App extends Component {
    render () {
        return (
            <div>app内容</div>
        );
    }
}
export default 

export default class RootComponent extends Component {
    render () {
        return (
            <Provider store={store}>
                connect(state => ({
                    a0: state.a.a0,
                    b0: state.b.b0,
                    c0: state.c.c0
                }), {
                    ...actions
                })(App)
            </Provider>
        )
    }
}

从上面使用上看,主要是 Provider Class 和 connect 函数两个东西。通过 connect 包装之后的 Component 和 Provider 通过 context 进行通信,分开来看,先说 Provider:

Provider.propTypes = {
    store: storeShape.isRequired,
    children: PropTypes.element.isRequired,
}
Provider.childContextTypes = {
    [storeKey]: storeShape.isRequired,
    [subscriptionKey]: subscriptionShape,
}

其源码中可以看出它接收两个 prop,一个是 store, 一个是 children。另外子孙组件想要和 Provider 通信,使用 store 和 subscriptionKey能力,就得通过 context[storeKey] 和 context[subscriptionKey] 使用,同时子孙组件也要提供可以使用 context 对象的依据(比如可以看 connect 函数源代码里面的高阶组件):

const contextTypes = {
    [storeKey]: storeShape,
    [subscriptionKey]: subscriptionShape,
  }

再看connect:

function connect(
    mapStateToProps,
    mapDispatchToProps,
    mergeProps,
    {
      pure = true,
      areStatesEqual = strictEqual,
      areOwnPropsEqual = shallowEqual,
      areStatePropsEqual = shallowEqual,
      areMergedPropsEqual = shallowEqual,
      ...extraOptions
    } = {}
  ) {
    const initMapStateToProps = match(mapStateToProps, mapStateToPropsFactories, 'mapStateToProps')
    const initMapDispatchToProps = match(mapDispatchToProps, mapDispatchToPropsFactories, 'mapDispatchToProps')
    const initMergeProps = match(mergeProps, mergePropsFactories, 'mergeProps')

    return connectHOC(selectorFactory, {
      // used in error messages
      methodName: 'connect',

       // used to compute Connect's displayName from the wrapped component's displayName.
      getDisplayName: name => `Connect(${name})`,

      // if mapStateToProps is falsy, the Connect component doesn't subscribe to store state changes
      shouldHandleStateChanges: Boolean(mapStateToProps),

      // passed through to selectorFactory
      initMapStateToProps,
      initMapDispatchToProps,
      initMergeProps,
      pure,
      areStatesEqual,
      areOwnPropsEqual,
      areStatePropsEqual,
      areMergedPropsEqual,

      // any extra options args can override defaults of connect or connectAdvanced
      ...extraOptions
    })
  }

connect 的结果就是返回一个高阶组件,这个高阶组件中的两个重要函数就是:

initSelector() {
    const sourceSelector = selectorFactory(this.store.dispatch, selectorFactoryOptions)
    this.selector = makeSelectorStateful(sourceSelector, this.store)
    this.selector.run(this.props)
}

initSubscription() {
    if (!shouldHandleStateChanges) return
    
    const parentSub = (this.propsMode ? this.props : this.context)[subscriptionKey]
    this.subscription = new Subscription(this.store, parentSub, this.onStateChange.bind(this))
    this.notifyNestedSubs = this.subscription.notifyNestedSubs.bind(this.subscription)
}

initSelector 判断 state 状态树或者 actions 是否更改,来决定被包裹组件的新 props,关键代码见:

const nextProps = sourceSelector(store.getState(), props)
    if (nextProps !== selector.props || selector.error)  {
        selector.shouldComponentUpdate = true
        selector.props = nextProps
        selector.error = null
}
...
render() {
    ...
    return createElement(WrappedComponent, this.addExtraProps(selector.props))
    ...
}

initSubscription 的主要作用就是监听 store 的 state 对象树是否变化,如果变化,就执行如下代码:

onStateChange() {
    this.selector.run(this.props) // 获取最新的props

    if (!this.selector.shouldComponentUpdate) {
      this.notifyNestedSubs()
    } else {
      this.componentDidUpdate = this.notifyNestedSubsOnComponentDidUpdate
      this.setState(dummyState)
    }
  }

也就是说先获取最新的 props, 这个 props 里面包括 states,然后判断是否需要重新渲染,如果需要,则触发 setState,引起高阶组件 react 生命周期的执行,再看 this.notifyNestedSubs() 这句,如果被包裹组件订阅了 state 变化,那么会依次执行所有的 listener,被包裹组件如果如果想订阅,需要借助 context,因为高阶组件里面定义了如下代码:

const childContextTypes = {
    [subscriptionKey]: subscriptionShape,
}

以上就是问题四的相关内容,使用过程中需要注意的是 connect 函数的第二个参数也就是 mapDispatchToProps 可以是个 actions 对象,也可以是一个方法,我习惯用对象,写起来方便,其实底层最终都是一样的,只是如果用的是对象的话,react-redux 内部会调用

bindActionCreators(mapDispatchToProps, dispatch)

把对象处理成新对象,这个新对象的values都是

(...args) => dispatch(actionCreator(...args))

所以就可以满足我们项目中 this.props.xxx(data) 来 dispatch 一个 action。

react-redux 中高阶组件是如何判断 props 更改,然后决定是否重新 render 的?

高阶组件的 props 来源两部分,分别是 state 对橡树里面的对象和 actions, 详细看 react-redux 包下面的 src/connect/selectorFactory.js 代码片段

function handleSubsequentCalls(nextState, nextOwnProps) {
    const propsChanged = !areOwnPropsEqual(nextOwnProps, ownProps)
    const stateChanged = !areStatesEqual(nextState, state)
    state = nextState
    ownProps = nextOwnProps

    if (propsChanged && stateChanged) return handleNewPropsAndNewState()
    if (propsChanged) return handleNewProps()
    if (stateChanged) return handleNewState()
    return mergedProps
  }

总结

redux 源代码到处充满着函数式编程以及调用 compose 柯里化,源代码量不多,简短干净,看了很舒服,上面的整个分析一句的 redux 版本是3.7.2,react-redux 版本5.1.1, 如果后续版本相关逻辑更改了请见谅。

评论

暂无评论