深入理解redux

  • A+
所属分类:React redux

createStore(reducer, preloadedState, enhancer) 创建一个仓库 返回仓库管理器对象


//返回的对象
return _ref2 = {
    dispatch: dispatch, //派发事件 store.dispatch( action )
    subscribe: subscribe, //
    getState: getState, //获取当前状态
    replaceReducer: replaceReducer //替换Reducer store.dispatch( reducer )
}

//实例02
import { createStore } from 'redux'

function todo( state = 1, { type, payload } ){
	switch( type ){
		case 'ADD':
			return ++state;
			break;
		case 'REDUCE':
			return --state;
			break;
		default:
			return state; 
	}
}

const enhancer = function( createStore ){ console.log( "create store!" ); return createStore }
const store = createStore( todo, 50, enhancer )

store.dispatch( { type: 'ADD', payload: 10 } )

console.log( store.getState() )// 51
//create store!
//51

//实例01
import { combineReducers, createStore } from 'redux'

function doAddAndSub( state = 0, { type, payload } ){
	switch( type ){
		case 'ADD':
			return ++state;
			break;
		case 'SUB':
			return --state;
			break;
		default:
			return state;
	}
}

function doMulAndDiv( state = 0, { type, payload } ){
	switch( type ){
		case 'MUL':
			return state*payload;
			break;
		case 'DIV':
			return state/payload;
			break;
		default:
			return state;
	}
}

const state = { doAddAndSub: 10, doMulAndDiv: 20 }
const action = { type: 'MUL', payload: 5 }

const reducer = combineReducers( { doAddAndSub, doMulAndDiv } )
const store = createStore( reducer, state )

console.log( store.getState() )//{ doAddAndSub: 10, doMulAndDiv: 20 }

store.dispatch( action )

console.log( store.getState() )//{ doAddAndSub: 10, doMulAndDiv: 100 }
weinxin
我的微信
欢迎来撩!!

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

目前评论:0   其中:访客  4   博主  0

    • 李向阳 李向阳 4

      没人哎…

      • 李向阳 李向阳 4

        你好

        • 李靖 李靖 4

          你好

          • 李向阳 李向阳 4

            你好