学习和理解 Redux提供可预测性的状态管理

| 2019-05-17

Redux的官方网站是这样描述Redux的,Redux是JavaScript应用程序的可预测状态容器。 当前Redux GitHub上有超过5w颗星,足以显示Redux的受欢迎程度。
 
  一,为什么要重做
  在讨论为什么使用Redux之前,让我们先讨论一下组件通信的方法。 有几种常见的组件通信方法:
 
  父子组件:道具,状态/回调回调进行通信
  单页应用程序:路由和传递值
  全局事件,例如EventEmitter
  在React中反应跨层组件数据传递上下文
  在小型,不太复杂的应用中,通常使用上述几种组件通信方法就足够了。
 
  但是,随着应用程序变得越来越复杂,数据状态(例如服务器响应数据,浏览器缓存的数据,UI状态值等)太多了,并且状态可能会频繁更改。 使用上述组件进行通信将非常复杂,繁琐,并且很难找到和调试相关问题。
 
  因此,状态管理框架(例如Vuex,MobX,Redux等)似乎非常必要,并且Redux是使用最广泛且生态最完整的框架之一。
 
  Redux数据流
  在使用Redux的应用程序中,遵循以下四个步骤:
 
  步骤1:使用store.dispatch(操作)来触发操作。 动作是描述将要发生的事情的对象。 如下:
{ type: 'LIKE_ARTICLE', articleId: 42 }
{ type: 'FETCH_USER_SUCCESS', response: { id: 3, name: 'Mary' } }
{ type: 'ADD_TODO', text: '金融前端.' }
步骤2:Redux将调用您提供的Reducer函数。
 
  步骤3:根Reducer将多个不同的Reducer功能组合到单独的状态树中。
 
  步骤4:Redux存储保存从root Reducer函数返回的完整状态树。
三项原则(三项原则)
  1.单一事实来源:单个数据源,整个应用程序状态存储在对象树中,并且仅存在于单个存储中。
 
  2.状态为只读:状态为只读。 您不能直接修改状态。 您只能通过触发操作来返回新状态。
 
  3.使用纯函数进行更改:使用纯函数来修改状态。
 
  四,Redux源码分析
  Redux源代码当前具有js和ts版本,本文首先介绍Redux源代码的js版本。  Redux源代码并不多,因此对于想要提高阅读源代码能力的开发人员来说,值得早日学习。
 
  Redux源代码主要分为6个核心js文件和3个工具js文件。 核心js文件是index.js,createStore.js,compose.js,combinedRuducers.js,bindActionCreators.js和applyMiddleware.js文件。
 
  接下来,我们来一步一步地学习。
 
  Index.js
  index.js是入口文件,并提供核心API,例如createStore,combinedReducers,applyMiddleware等。

export {
  createStore,
  combineReducers,
  bindActionCreators,
  applyMiddleware,
  compose,
  __DO_NOT_USE__ActionTypes
}
CreateStore.js
  createStore是Redux提供的用于生成唯一存储的API。 该商店提供诸如getState,dispatch和subscibe之类的方法。  Redux中的商店只能通过调度动作来找到相应的Reducer函数来更改动作。
export default function createStore(reducer, preloadedState, enhancer) {
...
}
从源代码可以知道,createStore接收三个参数:Reducer,preloadedState和Enhancer。
 
  Reducer是与可以修改存储中状态的操作相对应的纯函数。
 
  preloadedState表示先前状态的初始状态。
 
  增强器是由中间件通过applyMiddleware生成的增强功能。 存储中的getState方法将获取当前应用程序中存储中的状态树。
/**
 * Reads the state tree managed by the store.
 *
 * @returns {any} The current state tree of your application.
 */
function getState() {
  if (isDispatching) {
    throw new Error(
      'You may not call store.getState() while the reducer is executing. ' +
        'The reducer has already received the state as an argument. ' +
        'Pass it down from the top reducer instead of reading it from the store.'
    )
  }
  return currentState
}
调度方法用于调度动作。 这是唯一可以触发状态更改的方法。 订阅是在分派操作或状态更改时调用的侦听器。
 
  3,combinedReducers.js

/**
 * Turns an object whose values are different reducer functions, into a single
 * reducer function. It will call every child reducer, and gather their results
 * into a single state object, whose keys correspond to the keys of the passed
 * reducer functions.
 */
export default function combineReducers(reducers) {
  const reducerKeys = Object.keys(reducers)
     ...
  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
      //判断state是否发生改变
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey
    }
    //根据是否发生改变,来决定返回新的state还是老的state
    return hasChanged ? nextState : state
  }
}

从源码可以知道,入参是 Reducers,返回一个function。combineReducers就是将所有的 Reducer合并成一个大的 Reducer 函数。核心关键的地方就是每次 Reducer 返回新的state的时候会和老的state进行对比,如果发生改变,则hasChanged为true,触发页面更新。反之,则不做处理。

4、bindActionCreators.js

/**
 * Turns an object whose values are action creators, into an object with the
 * same keys, but with every function wrapped into a `dispatch` call so they
 * may be invoked directly. This is just a convenience method, as you can call
 * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
 */
function bindActionCreator(actionCreator, dispatch) {
  return function() {
    return dispatch(actionCreator.apply(this, arguments))
  }
}
 
export default function bindActionCreators(actionCreators, dispatch) {
  if (typeof actionCreators === 'function') {
    return bindActionCreator(actionCreators, dispatch)
  }
    ...
    ...
  const keys = Object.keys(actionCreators)
  const boundActionCreators = {}
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i]
    const actionCreator = actionCreators[key]
    if (typeof actionCreator === 'function') {
      boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
    }
  }
  return boundActionCreators
}

bindActionCreator是将单个actionCreator绑定到dispatch上,bindActionCreators就是将多个actionCreators绑定到dispatch上。

bindActionCreator就是将发送actions的过程简化,当调用这个返回的函数时就自动调用dispatch,发送对应的action。

bindActionCreators根据不同类型的actionCreators做不同的处理,actionCreators是函数就返回函数,是对象就返回一个对象。主要是将actions转化为dispatch(action)格式,方便进行actions的分离,并且使代码更加简洁。

5、compose.js

/**
 * Composes single-argument functions from right to left. The rightmost
 * function can take multiple arguments as it provides the signature for
 * the resulting composite function.
 *
 * @param {...Function} funcs The functions to compose.
 * @returns {Function} A function obtained by composing the argument functions
 * from right to left. For example, compose(f, g, h) is identical to doing
 * (...args) => f(g(h(...args))).
 */
 
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)))
}

compose是函数式变成里面非常重要的一个概念,在介绍compose之前,先来认识下什么是 Reduce?官方文档这么定义reduce:reduce()方法对累加器和数组中的每个元素(从左到右)应用到一个函数,简化为某个值。compose是柯里化函数,借助于Reduce来实现,将多个函数合并到一个函数返回,主要是在middleware中被使用。

6、applyMiddleware.js

/**
 * Creates a store enhancer that applies middleware to the dispatch method
 * of the Redux store. This is handy for a variety of tasks, such as expressing
 * asynchronous actions in a concise manner, or logging every action payload.
 */
export default function applyMiddleware(...middlewares) {
  return createStore => (...args) => {
    const store = createStore(...args)
    ...
    ...
    return {
      ...store,
      dispatch
    }
  }
}

applyMiddleware.js文件提供了middleware中间件重要的API,middleware中间件主要用来对store.dispatch进行重写,来完善和扩展dispatch功能。

那为什么需要中间件呢?

首先得从Reducer说起,之前 Redux三大原则里面提到了reducer必须是纯函数,下面给出纯函数的定义:

  • 对于同一参数,返回同一结果
  • 结果完全取决于传入的参数
  • 不产生任何副作用

至于为什么reducer必须是纯函数,可以从以下几点说起?

  • 因为 Redux 是一个可预测的状态管理器,纯函数更便于 Redux进行调试,能更方便的跟踪定位到问题,提高开发效率。
  • Redux 只通过比较新旧对象的地址来比较两个对象是否相同,也就是通过浅比较。如果在 Reducer 内部直接修改旧的state的属性值,新旧两个对象都指向同一个对象,如果还是通过浅比较,则会导致 Redux 认为没有发生改变。但要是通过深比较,会十分耗费性能。最佳的办法是 Redux返回一个新对象,新旧对象通过浅比较,这也是 Reducer是纯函数的重要原因。

Reducer是纯函数,但是在应用中还是会需要处理记录日志/异常、以及异步处理等操作,那该如何解决这些问题呢?

这个问题的答案就是中间件。可以通过中间件增强dispatch的功能,示例(记录日志和异常)如下:

const store = createStore(reducer);
const next = store.dispatch;
 
// 重写store.dispatch
store.dispatch = (action) => {
    try {
        console.log('action:', action);
        console.log('current state:', store.getState());
        next(action);
        console.log('next state', store.getState());
    } catch (error){
        console.error('msg:', error);
    }
}

五、从零开始实现一个简单的Redux

既然是要从零开始实现一个Redux(简易计数器),那么在此之前我们先忘记之前提到的store、Reducer、dispatch等各种概念,只需牢记Redux是一个状态管理器。

首先我们来看下面的代码:

let state = {
    count : 1
}
//修改之前
console.log (state.count);
//修改count的值为2
state.count = 2//修改之后
console.log (state.count);

我们定义了一个有count字段的state对象,同时能输出修改之前和修改之后的count值。但此时我们会发现一个问题?就是其它如果引用了count的地方是不知道count已经发生修改的,因此我们需要通过订阅-发布模式来监听,并通知到其它引用到count的地方。因此我们进一步优化代码如下:

let state = {
    count: 1
};
//订阅
function subscribe (listener) {
    listeners.push(listener);
}
function changeState(count) {
    state.count = count;
    for (let i = 0; i < listeners.length; i++) {
        const listener = listeners[i];
        listener();//监听
    }
}

此时我们对count进行修改,所有的listeners都会收到通知,并且能做出相应的处理。但是目前还会存在其它问题?比如说目前state只含有一个count字段,如果要是有多个字段是否处理方式一致。同时还需要考虑到公共代码需要进一步封装,接下来我们再进一步优化:

const createStore = function (initState) {
    let state = initState;
    //订阅
    function subscribe (listener) {
        listeners.push(listener);
    }
    function changeState (count) {
        state.count = count;
        for (let i = 0; i < listeners.length; i++) {
            const listener = listeners[i];
            listener();//通知
        }
    }
    function getState () {
        return state;
    }
    return {
        subscribe,
        changeState,
        getState
    }
}

我们可以从代码看出,最终我们提供了三个API,是不是与之前Redux源码中的核心入口文件index.js比较类似。但是到这里还没有实现Redux,我们需要支持添加多个字段到state里面,并且要实现Redux计数器。

let initState = {
    counter: {
        count : 0
    },
    info: {
        name: '',
        description: ''
    }
}
let store = createStore(initState);
//输出count
store.subscribe(()=>{
    let state = store.getState();
    console.log(state.counter.count);
});
//输出info
store.subscribe(()=>{
    let state = store.getState();
    console.log(`${state.info.name}:${state.info.description}`);
});

通过测试,我们发现目前已经支持了state里面存多个属性字段,接下来我们把之前changeState改造一下,让它能支持自增和自减。

//自增
store.changeState({
    count: store.getState().count + 1
});
//自减
store.changeState({
    count: store.getState().count - 1
});
//随便改成什么
store.changeState({
    count: 金融
});

我们发现可以通过changeState自增、自减或者随便改,但这其实不是我们所需要的。我们需要对修改count做约束,因为我们在实现一个计数器,肯定是只希望能进行加减操作的。所以我们接下来对changeState做约束,约定一个plan方法,根据type来做不同的处理。

function plan (state, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return {
        ...state,
        count: state.count + 1
      }
    case 'DECREMENT':
      return {
        ...state,
        count: state.count - 1
      }
    default:
      return state
  }
}
let store = createStore(plan, initState);
//自增
store.changeState({
    type: 'INCREMENT'
});
//自减
store.changeState({
    type: 'DECREMENT'
});

我们在代码中已经对不同type做了不同处理,这个时候我们发现再也不能随便对state中的count进行修改了,我们已经成功对changeState做了约束。我们把plan方法做为createStore的入参,在修改state的时候按照plan方法来执行。到这里,恭喜大家,我们已经用Redux实现了一个简单计数器了。

这就实现了 Redux?这怎么和源码不一样啊

然后我们再把plan换成reducer,把changeState换成dispatch就会发现,这就是Redux源码所实现的基础功能,现在再回过头看Redux的数据流图是不是更加清晰了。

六、Redux Devtools

Redux devtools是Redux的调试工具,可以在Chrome上安装对应的插件。对于接入了Redux的应用,通过 Redux devtools可以很方便看到每次请求之后所发生的改变,方便开发同学知道每次操作后的前因后果,大大提升开发调试效率。

如上图所示就是 Redux devtools的可视化界面,左边操作界面就是当前页面渲染过程中执行的action,右侧操作界面是State存储的数据,从State切换到action面板,可以查看action对应的 Reducer参数。切换到Diff面板,可以查看前后两次操作发生变化的属性值。

七、总结

Redux 是一款优秀的状态管理器,源码短小精悍,社区生态也十分成熟。如常用的react-redux、dva都是对 Redux 的封装,目前在大型应用中被广泛使用。这里推荐通过 Redux官网以及源码来学习它核心的思想,进而提升阅读源码的能力。


编辑:航网科技 来源:腾讯云代理 本文版权归原作者所有 转载请注明出处

在线客服

微信扫一扫咨询客服


全国免费服务热线
0755-36300002

返回顶部