【20160928】Redux入门教程【推荐】
zhongxia245 opened this issue · 3 comments
Redux入门教程
Redux看了很多教程,很多文章,知道具体怎么使用,但是对于里面的原理,以及如何串起来不是很了解。后面看了 阮一峰阮老师的 《redux 入门教程》,茅塞顿开。
参考文章
还是需要看下 redux 和 react-redux 的代码, redux中间件的代码看过了 redux-thunk ,redux-promise 这些中间件都比较简单,不过需要理解下
分析了下 redux 和 中间件 redux-thunk的源码
redux主要就是观察者模式的应用,action相当于注册事件的类型和参数,reducer相当于事件的处理方法, dispatch就是派发事件。
redux 中的 createStore 可以理解成实例化一个对象(仓库),对象里面有一个属性state,用来保存所有的数据。
react 和 redux 是没有关联关系的,redux 内部实现一个观察者模式,来事件action的派发和处理, 并用 一个state对象来保存数据。
redux 里面主要有几个方法,
createStore,
combineReducers,
bindActionCreators,
applyMiddleware,
compose
compose 是一个工具方法
applyMiddleware 使用中间件(在 派发出 action 和 执行 reducer 中间添加处理方法)
combineReducers 把reducer拆开写, 然后合并起来
bindActionCreators 给 actionCreate 套一层,
//ActionCreator
export function addTodo(text) {
return {
type: 'ADD_TODO',
text
};
}
//不使用 bindActionCreators的用法
let action = TodoActionCreators.addTodo('Use Redux');
dispatch(action);
//使用 bindActionCreator的用法
let boundActionCreators = bindActionCreators(TodoActionCreators, dispatch);
createStore 创建一个 store 来保存 state, 说白了 就是创建一个对象。 【参考下面第二个评论】
下面代码摘自 Redux 入门教程(一):基本用法
redux Store 的简单实现
const createStore = (reducer) => {
let state;
let listeners = [];
const getState = () => state;
const dispatch = (action) => {
state = reducer(state, action);
listeners.forEach(listener => listener());
};
const subscribe = (listener) => {
listeners.push(listener);
return () => {
listeners = listeners.filter(l => l !== listener);
}
};
dispatch({});
return { getState, dispatch, subscribe };
};
redux 中的 combineReducers 简单实现
注意,使用 combineReducers, 注意 State 的属性名必须与子 Reducer 同名,具体参照 Redux 入门教程(一):基本用法
const combineReducers = reducers => { return (state = {}, action) => { return Object.keys(reducers).reduce( (nextState, key) => { nextState[key] = reducers[key](state[key], action); return nextState; }, {} ); }; };
Redux的工作流程
首先,用户发出 Action。
store.dispatch(action);
然后,Store 自动调用 Reducer,并且传入两个参数:当前 State 和收到的 Action。 Reducer 会返回新的 State 。
let nextState = todoApp(previousState, action);
State 一旦有变化,Store 就会调用监听函数。
// 设置监听函数
store.subscribe(listener);
listener可以通过store.getState()得到当前状态。如果使用的是 React,这时可以触发重新渲染 View。
function listerner() {
let newState = store.getState();
component.setState(newState);
}