react-thunk 项目实践

2019-07-25  本文已影响0人  _一九九一_

简介:

实现动态菜单路由导航

store.js:

import { createStore, applyMiddleware, compose } from 'redux';
import reducer from '../reducer';
import thunk from 'redux-thunk';
 
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const enhancer = composeEnhancers(applyMiddleware(thunk));
const configureStore = createStore(
  reducer,
  enhancer
);

export default configureStore;

action:

import { get_menu_tree } from '../../services/api';
 
export const GET_MENU_TREE = 'GET_MENU_TREE';   

// 获取菜单
const getMenuTreeAction = (responseData) => ({
  type: GET_MENU_TREE, 
  responseData
})

 // 先通过dispath发起一个异步, react-thuunk 处理异步拿到 responseData 以后 发起一个同步dispath 更改state
export const getMenuTree = () => (dispatch) => {
  get_menu_tree().then(res => {
    const { responseData } = res.data;
    dispatch(getMenuTreeAction(responseData));
  })
}

reducer:

import { combineReducers } from 'redux';
import { GET_MENU_TREE } from './../action/actionTypes';

const getTree = (state = {}, action) => { 
  switch (action.type) {
    case GET_MENU_TREE:
      return Object.assign({}, state, {
        tree: action
      })  
    default:
      return state
  }
}

const reducer = combineReducers({
  getTree,
})

export default reducer

容器组件:

const mapStateToProps = (state) => {
}

const mapDispatchToProps = (dispatch) => {
  return {
    getMenuTreeFn: () => dispatch(getMenuTree()) 
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App)
上一篇下一篇

猜你喜欢

热点阅读