美文网首页
react-thunk 项目实践

react-thunk 项目实践

作者: _一九九一_ | 来源:发表于2019-07-25 17:40 被阅读0次

    简介:

    • redux 可以通过 dispath 一个action 后, 更新state,这叫做同步;
    • 但是action 发出以后,想过一段时间再执行 Reducer,或者请求接口然后更改state,这就是异步
    • 这篇文章就是通过react-thunk实现reducer的动态action

    实现动态菜单路由导航

    store.js:

    • 设置thunk
    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)
    

    相关文章

      网友评论

          本文标题:react-thunk 项目实践

          本文链接:https://www.haomeiwen.com/subject/trqkrctx.html