本文作者:IMWeb 陈映平 原文出处:IMWeb社区 未经同意,禁止转载
其实,redux的核心概念就是store、action、reducer,从调用关系来看如下所示
store.dispatch(action) --> reducer(state, action) --> final state
可以先看下面的极简例子有个感性的认识,下面会对三者的关系进行简单介绍
// reducer方法, 传入的参数有两个 // state: 当前的state // action: 当前触发的行为, {type: 'xx'} // 返回值: 新的state var reducer = function(state, action){ switch (action.type) { case 'add_todo': return state.concat(action.text); default: return state; } }; // 创建store, 传入两个参数 // 参数1: reducer 用来修改state // 参数2(可选): [], 默认的state值,如果不传, 则为undefined var store = redux.createStore(reducer, []); // 通过 store.getState() 可以获取当前store的状态(state) // 默认的值是 createStore 传入的第二个参数 console.log('state is: ' + store.getState()); // state is: // 通过 store.dispatch(action) 来达到修改 state 的目的 // 注意: 在redux里,唯一能够修改state的方法,就是通过 store.dispatch(action) store.dispatch({type: 'add_todo', text: '读书'}); // 打印出修改后的state console.log('state is: ' + store.getState()); // state is: 读书 store.dispatch({type: 'add_todo', text: '写作'}); console.log('state is: ' + store.getState()); // state is: 读书,写作
可以结合上面的代码来看下面几段解释
getState
、dispatch
。前者用来获取store的状态(state),后者用来修改store的状态。// 创建store, 传入两个参数 // 参数1: reducer 用来修改state // 参数2(可选): [], 默认的state值,如果不传, 则为undefined var store = redux.createStore(reducer, []); // 通过 store.getState() 可以获取当前store的状态(state) // 默认的值是 createStore 传入的第二个参数 console.log('state is: ' + store.getState()); // state is: // 通过 store.dispatch(action) 来达到修改 state 的目的 // 注意: 在redux里,唯一能够修改state的方法,就是通过 store.dispatch(action) store.dispatch({type: 'add_todo', text: '读书'});
type
字段来标识这个行为的类型。所以,下面的都是合法的action{type:'add_todo', text:'读书'} {type:'add_todo', text:'写作'} {type:'add_todo', text:'睡觉', time:'晚上'}
// reducer方法, 传入的参数有两个 // state: 当前的state // action: 当前触发的行为, {type: 'xx'} // 返回值: 新的state var reducer = function(state, action){ switch (action.type) { case 'add_todo': return state.concat(action.text); default: return state; } };
看到xxCreator
总能让人联想到工厂模式,没错,在redux里,actionAreator其实就是action的工厂方法,可以参考下面例子。
actionCreator(args) => action
var addTodo = function(text){ return { type: 'add_todo', text: text }; }; addTodo('睡觉'); // 返回:{type: 'add_todo', text: '睡觉'}
在redux里,actionAreator并非是必需的。不过建议用actionAreator代替普通action对象的直接传递。除了能够减少代码量,还可以大大提高代码的可维护性。想象下面的场景
再来看回文章开头的例子,应用actionAreator后的代码示例。
store.dispatch(addTodo('睡觉')); console.log('state is: ' + store.getState()); // state is: 读书,写作,睡觉
redux中文文档:http://camsong.github.io/redux-in-chinese/index.html
redux英文文档:http://redux.js.org/index.html
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句