import {connect} from 'react-redux'//参数一 mapStateToprops = {state} => {return {num:state.counter}}//参数二 mapDispatchToProps = dispatch => {return {add:()=>dispatch({type:'add',payload})}@connect( state => ({num:state}), { add: ()=>({type:'add'}), minus:()=>({type:'minus'}), asyncAdd: ()=>dispatch=>{ //异步返回的是函数 setTimeout(()=>{ dispatch({type:'add',100}) },1000) } })class ReduxTest extends Component {}
// store.jsimport {createStore,applyMiddleware} from 'redux';import logger from 'redux-logger'const store = createStore(counterReducer,applyMiddleware(logger,thunk));//中间件有顺序export default store
redux 核心实现
- 存储状态state
- 获取状态getState
- 更新状态dispatch
- 变更订阅subscribe
export default createStore(reducer,enhancer){ //如果存在enhancer if(enhancer){ //让createStore 变强 enhancer(createStore)(reducer) } let currentState = undefined; const currentListeners = [];//回调函数数组 function getState(){ return currentState } function dispatch(action){ currentState = reducer(currentState,action) //变更通知 发布订阅模式 currentListeners.forEach(v=>v()) return action } function subscribe(cb){ currentListeners.push(cb); } //初始化状态 dispatch({type:'@#$$JID'}) return { getState, dispatch, subscribe }}export function applMidderware(...midderwares){ return createStore => (...args)=>{ //完成createStore工作 const store = createStore(...args); let dispatch = store.dipatch; cosnt midApi = { getState: store.getState, dispatch:(...args) => dispatch(...args) } //将来中间件的函数签名如下: function({}){} const chain = middleware.map(mw => mw(midApi)) dispatch = compose(...chain)(store.dispatch) //返回全新的store 仅更新强化过的dispatch return { ...store, dispatch } }}export function compose(...funcs){ return funcs.reduce((left,right)=> (...args)=> right(left(...args)); }==============================const counterReducer = function(state=0,action){ const num = action.payload ||1; switch(action.type){ case "add": return state + num; case "minus": return state - num; default: return state; }}const store = createStore(counterReducer)
function logger({dispatch,getState}){ //返回真正中间件任务执行函数 return dispatch => action => { console.log(action.type+'执行了!!'); return dispatch(action);}