-
Notifications
You must be signed in to change notification settings - Fork 33
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
【20160928】Redux入门教程【推荐】 #26
Comments
分析了下 redux 和 中间件 redux-thunk的源码
react 和 redux 是没有关联关系的,redux 内部实现一个观察者模式,来事件action的派发和处理, 并用 一个state对象来保存数据。 redux 里面主要有几个方法, createStore,
combineReducers,
bindActionCreators,
applyMiddleware,
compose compose 是一个工具方法 //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 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 简单实现
|
首先,用户发出 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);
} |
Redux入门教程
参考文章
The text was updated successfully, but these errors were encountered: