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是这个库的主要方法,具体用法见上面,不多说了。

     

  • 相关阅读:
    Lua IDE工具-Intellij IDEA+lua插件配置教程(Chianr出品)
    XLua热更新用法全流程总结(所有容易出问题的点)
    Unity用GUI绘制Debug/print窗口/控制台-打包后测试
    Unity在UI界面上显示3D模型/物体,控制模型旋转
    Eclipse的Debug调试技巧
    IntelliJ Idea 常用快捷键列表
    设计模式之代理模式的静态代理和动态代理
    设计模式之单例模式
    linux下防火墙设置
    FastDFS简介和安装
  • 原文地址:https://www.cnblogs.com/yanchenyu/p/7805469.html
Copyright © 2011-2022 走看看