JerryZhai2019 / gitkills

0 stars 0 forks source link

redux-thunk中间件是什么?使用 #13

Open JerryZhai2019 opened 1 year ago

JerryZhai2019 commented 1 year ago

Redux的核心概念其实很简单:将需要修改的state都存入到store里,发起一个action用来描述发生了什么,用reducers描述action如何改变state tree。创建store的时候需要传入reducer,真正能改变store中数据的是store.dispatchAPI。

概念 dispatch一个action之后,到达reducer之前,进行一些额外的操作,就需要用到middleware。你可以利用Redux middleware来进行日志记录、创建崩溃报告、调用异步接口或者路由 。。。。换言之,中间件都是对store.dispatch()的增强

Redux事件流 是由组件dispatch 发起一个action 到reducer, reducer根据type类型,重新计算(注意:reducer是一个纯函数),返回一个新的state给store,再由store给对应的组件。其中涉及到异步的操作会使用到redux-thunk

JerryZhai2019 commented 1 year ago

Redux基础用法 impot { createStore, applymiddleware, compose, Store, AnyAction} from 'redux'; import thunk from 'redux-thunk' import reducers from '../common/reducers'; import { storeState } from '../common/types';

export default function configureStore():Store<StoreState, AnyAction>{ const composeEnhancers = compose; const enhancer = composeEnhance( applyMiddleware(thunk) const store = createStore( reducers, // initialState, enhancer ); )

}、

定义常量

/map/types/index

export const RIGHT_ISASSETSOURCE = 'right_isAssetSource'; export const ACTIVE_ASSET = 'active_asset';

/设置state const initialState:MapmoduleState = { asset: null, // active asset isAssetSource: true // asset source(list || map) };

export type MapmoduleState = { asset: any, isAssetSource: boolean }

创建action export function activeAsset(id:any) { if(!id){ return (dispatch:any)=>{ dispatch({ type: ACTIVE_ASSET, data: '' }); }; }

return (dispatch:any, getState:any)=>{ getAssetById(id).then((res:any)=>{ dispatch({ type: ACTIVE_ASSET, data: res }); const { isAssetSource } = getState().mapmodule; const { map } = getState().config; const newCenter = getMarkerPos(res, map);

  if(isAssetSource){
    dispatch(mapView?.(map.scaleMax, newCenter,null));
  }
});

}; }

export function rightIsAssetSource(isAssetSource:any) { return { type: RIGHT_ISASSETSOURCE, data: isAssetSource }; }

创建reducer export default function mapmodule( // eslint-disable-next-line default-param-last state:MapmoduleState=initialState, action:AnyAction) { switch(action.type) { case ACTIVE_ASSET: return { ...state, asset:action.data}; case RIGHT_ISASSETSOURCE : return { ...state, isAssetSource:action.data}; default: return state; } }

使用 //从props中拿到,下面已经通过connect注入了 const { activeAsset, rightIsAssetSource } = props;

// 使用connect注入state和dispatch export default connect( (state:StoreState)=>({ assets: state.mapmodule.assets, }), (dispatch:ThunkDispatch<StoreState, void, AnyAction>) => ({ activeAsset: (id:string)=>dispatch(actionActiveAsset(id)),

rightIsAssetSource: (isAssetSource:boolean)=>dispatch(actionRightIsAssetSource(isAssetSource)),

}) )(withStyles(()=>({ root: { }, }))(Index));