Redux学习之二:从action到store?
redux里面的概念很多,有Action、ActionCreator、reducer、store、middleware、Provider、Connect……概念不理解,就是眉毛胡子一把抓,弄不出头绪。redux的概念,通过一张图大家就一目了然了。 这张图大致可以概括redux的整个流程。从图中我们可以看出,Action是数据流动的开始,Reducer负责业务逻辑处理,store是整个流程的中轴。 1、你从哪里来?——谈谈actions的起源 redux里的action和flux里的action大体上一致,不同的是设计理念的差别。flux里的action是以函数的形式,但在redux里,action被设计成普通的js对象。 { function addTodo(text) { return { type: ADD_TODO,text }; } dispatch(addTodo(text)); 2、条条大路通哪里?——看看reducer的神奇 action表示发生了什么事情,表明了有事情发生,肯定会对应用的数据产生影响。我们知道,React组件内的数据都是以state的形式存在的,state代表着数据结构。那么就要问了,action的发生到底会对state产生什么影响。这就是reducer的作用了。 (previousState,action) => newState 这种设计来源于函数式编程思想,简单,易懂,没有副作用。 function todoApp(state = initialState,action) { return Object.assign({},state,{ visibilityFilter: action.filter }); default: return state; } 3、看看你是谁?——揭开store的面纱 首先我们看文档里怎么描述的:
这就说明,Store负责把reducer和action结合的作用。store怎么创建?一般是通过下面的代码: const store = createStore(reducer); 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,replaceReducer 可以看出redux里的store有点像flux里的dispatcher的作用,产生action可以通过store.dispatch发送出去,想监听状态可以通过store.subscribe订阅。 以上就是我对redux流程前半部分的理解,请批评指正。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |