学生教材网 >程序设计 > 开源项目 > 程序开发 > 浏览文章

Redux学习之二:从action到store?[页4]

来源:网络编辑:佚名时间:2015-09-20人气:

新恋爱时代迅雷下载,老婆生日礼物,云南公务员论坛

return Object.assign({}, state, {
  visibilityFilter: action.filter
});

default:

return state;

}
}
可以看出,业务逻辑部分都是在reducer里处理。这就涉及一个问题,一个应用里有很多逻辑部分,都放在一个reducer里面会造成非常的臃肿。实际过程中,把业务进行分拆,然后通过combineReducer函数合并成一个reducer。详细可以看这里:
https://github.com/rackt/redux/blob/master/docs/basics/Reducers.md
切记,在reducer不要改变旧的state值。

3、看看你是谁?——揭开store的面纱

首先我们看文档里怎么描述的:

The Store is the object that brings themtogether.(them指的是action和reducer)

It’s important to note that you’ll only have a single store in a Redux application.

这就说明,Store负责把reducer和action结合的作用。store怎么创建?一般是通过下面的代码:

const store = createStore(reducer);
这个createStore又是什么函数,我们看看createStore.js源码:

import isPlainObject from './utils/isPlainObject';
export var ActionTypes = {
  INIT: '@@redux/INIT'
};
export default function createStore(reducer, initialState) {
  if (typeof reducer !== 'function') {
    throw new Error('Expected the reducer to be a function.');
  }

  var currentReducer = reducer;
  var currentState = initialState;
  var listeners = [];
  var isDispatching = false;

  function getState() {
    return currentState;
  }

  function subscribe(listener) {
    listeners.push(listener);

    return function unsubscribe() {
      var index = listeners.indexOf(listener);
      listeners.splice(index, 1);
    };
  }

  function dispatch(action) {
    if (!isPlainObject(action)) {
      throw new Error(
        'Actions must be plain objects. ' +
        'Use custom middleware for async actions.'
      );
    }

    if (typeof action.type === 'undefined') {
      throw new Error(
        'Actions may not have an undefined "type" property. ' +
        'Have you misspelled a constant?'
      );
    }

    if (isDispatching) {
      throw new Error('Reducers may not dispatch actions.');
    }

    try {
      isDispatching = true;
      currentState = currentReducer(currentState, action);
    } finally {
      isDispatching = false;
    }

    listeners.slice().forEach(listener => listener());
    return action;
  }

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


  dispatch({ type: ActionTypes.INIT });

  return {
    dispatch,
    subscribe,
    getState,
    replaceReducer
  };
}

我们可以看到createStore返回的是一个对象,该对象有四种方法,分别是:

dispatch,
subscribe,
getState,
replaceReducer

可以看出redux里的store有点像flux里的dispatcher的作用,产生action可以通过store.dispatch发送出去,想监听状态可以通过store.subscribe订阅。
值得注意的是,程序初始化的时候,redux会发送一个类型为@@redux/INIT的action,来初始化state。

以上就是我对redux流程前半部分的理解,请批评指正。

xCodeGhost 事件专题总结

最近闹的沸沸扬扬的xCodeGhost事件,一开始是由阿里的蒸米、讯迪在乌云发布了深度的病毒解析,随后腾讯安全研究员也跟进分析。由于此病毒感染了包括网易云音乐、滴滴出行等一批用户量很大的手机APP,在知乎也引起了网友的热议,知乎网友称此事件的影响难以估量。最后看雪的安全研究员也发布了一款病毒检测工具。

热门推荐