const Redux = require('redux'); const reducer = function(state, action) { if (action.type === 'changeName') { // const newState = JSON.parse(JSON.stringify(state));
// 不能直接修改原来的state对象 return Object.assign({}, state, {name: action.name}); } else { // 未配置情况,返回原来的state return state; } } // 参数: reducer(return state), [init state] const store = Redux.createStore(reducer, {name: 'init name', age: 20}); // 订阅监听 store.subscribe(() => console.log(store.getState())); // 同步dispatch const action = { type: 'changeName', name: 'lily' } store.dispatch(action);
redux中对于store的api包括以下几个:
1. createStore
2. reducer函数
3. getState()
4. subscribe(callback)
5. dispatch(action) dispatch本身只能进行同步触发,若要进行异步触发,需要借助一些异步的语法。
// 借助promise实现异步触发 function callAction() { const actionPromise = new Promise((resovle, reject) => { const action = { type: 'changeName', name: 'lily' }; resovle(action); }) actionPromise.then((action) => { store.dispatch(action); }) } callAction();
对于reducer,redux提供了一个api——combineReducers.
首先,看一下其实现原理
// combineReducers 实现原理 // function combineReducers(reducers) { // return function reducer(state, action) { // let newState = {}; // for (let key in reducers) { // 把state中每一个属性值作为state,带入对应的Reducer中进行处理 // newState[key] = reducers[key](state[key],action); // } // } // }
const Redux = require('redux'); // const state = { a: [], b: [], c:{ name: '', group: []} }; const aReducer = function(state, action) { if (typeof state === 'undefined') return []; switch (action.type) { case 'a': return state.concat([action.data]); default: return state; } } const bReducer = function(state, action) { if (typeof state === 'undefined') return []; switch (action.type) { case 'b': return state.concat([action.data]); default: return state; } } const cNameReducer = function(state, action) { if (typeof state == 'undefined') return ''; switch (action.type) { case 'c': return action.name; default: return state; } } const cGroupReducer = function(state, action) { // state对应的是group的value if (typeof state === 'undefined') return []; switch(action.type) { case 'c': return state.concat(action.item); default: return state; } } const cReducer = function (state, action) { // state对应的是c的value if (typeof state === 'undefined') return {name: '', group: []}; switch(action.type) { case 'c': // 返回reducer处理函数,然后调用 return Redux.combineReducers({name: cNameReducer, group: cGroupReducer})(state, action); default: return state; } } // 每个属性对应的reducer const reducers = Redux.combineReducers({a: aReducer, b: bReducer, c: cReducer}); const store = Redux.createStore(reducers, {a: [111], b: [222], c:{ name: 'hi', group:[] }}); store.subscribe(() => console.log(store.getState())); const action1 = { type: 'b', data: 'lead' }; const action2 = { type: 'a', data: 'tail' } const action3 = { type: 'c', name: 'jkp', item: 'pp' } store.dispatch(action1); store.dispatch(action2); store.dispatch(action3);