zoukankan      html  css  js  c++  java
  • redux学习日志:关于异步action

    当我们在执行某个动作的时候,会直接dispatch(action),此时state会立即更新,但是如果这个动作是个异步的呢,我们要等结果出来了才能知道要更新什么样的state(比如ajax请求),那就没办法了,所以此时要用异步action。

    这里一定要引入redux-thunk这个库,通过使用中间件Middleware来把从action到reducer这个过程给拆分成很多个小过程,这样我们就能在中间随时查找此刻的状态以及执行一些其他动作了。具体的Middleware和redux-thunk以后再介绍,这里直接上代码如何用,只要在store里面这样写就可以了:

    import {createStore,applyMiddleware} from 'redux'
    import thunk from 'redux-thunk'
    import {reducers} from '../reducers/reducers'
    
    const initState = {
        ...
    };
    
    export const store = createStore(
        reducers,
        initState,
        applyMiddleware(thunk)
    )  

    此时就可以在action文件里面开始写异步action了,先上代码:

    function loginAction(data){
        return (dispatch,getState) => {
                setTimeout(function() {
                    if(getState(num) > 0) {
                         dispatch(action1(data))
                    } else {
                         dispatch(action2(data))
                    }
                }, 2000); 
        }
    }        

    这个loginAction表示动作触发2秒之后,检测一下当前状态num,如果此时的num>0,就dispatch第一个action1,否则dispatch第二个action2,这里模拟了一个异步的过程,在执行loginAction的时候还不知道要触发哪个action,2秒之后才知道。这里的两个参数dispatch和getState是中间件提供的。

    最后来列举一个常用的ajax调用的示例,这里要用到一个库,名字比较奇怪“isomorphic-fetch”,它的用法类似于Promise的用法,直接上代码:

    import fetch from 'isomorphic-fetch';
    import {serviceIpHotelMaster} from '../services/config';
    import {createHashHistory} from 'history'
    
    const history = createHashHistory();
    
    // 登录action
    function loginAction(data){
        return dispatch => {
            return fetch(`${serviceIpHotelMaster}/HostelAccount/Login?UserName=${data.userName}&PassWord=${data.password}&callback`,{method: 'get'})
                .then(response => response.json())
                .then(response => {
                    if(response.ResultCode==0){
                        dispatch(setHotelData(response.Data));
                        dispatch(setToken(response.Data.Token));
                        history.push('/roomList');
                    }
                })
                
        }
    } 

     这里是一个登录的过程,fetch是这个库的主要方法,具体用法见上面,不多说了。

     

  • 相关阅读:
    .NET设计模式系列文章《转》
    sharpwebmail邮件管理系统开源 下载及使用方法
    POJ 1949 DP?
    POJ 1948 DP
    POJ 1945 暴搜+打表 (Or 暴搜+判重)
    POJ 1944 并查集(模拟)
    POJ 3259 Wormholes SPFA判负环
    POJ 3268 Dijkstra+priority_queue或SPFA
    POJ 3299 模拟
    POJ 3342 树形DP+Hash
  • 原文地址:https://www.cnblogs.com/yanchenyu/p/7805469.html
Copyright © 2011-2022 走看看