• Redux系列实现异步请求


    一、简介

            普通的action处理会自动分派给对应的reducer处理。异步的action会经过Middlewares进行处理,异步完成后再交由对应的reducer处理。

    1.Middleware

            (1) 截获action

                    判断action是否是一个promise操作。

            (2) 发出action

    二、代码实现

            举个例子,获取文章列表。action返回的是一个promise,有开始请求列表、获取列表成功、获取列表失败三个action。当ajax异步请求执行后,会发送对应的action,reducer会根据action处理state,ui会渲染对应state的变更。

            

    1. //redux state
    2. const initialState = {data:null, fetchRebbitListPending:false, fetchRebbitListError:null}
    3. // 获取文章列表 action
    4. export function fetchRedditList(args = {}){
    5. return dispatch => {
    6. // 发送一个开始获取列表事件
    7. dispatch({type: FETCH_REDDIT_LIST_BEGIN});
    8. // 发送ajax请求,获取数据
    9. const promise = new Promise({resolve,reject} =>{
    10. const doRequest = axios.get("http://www.reddit.com/r/reactjs.json");
    11. doRequest.then(
    12. res => {
    13. dispatch({
    14. type: FETCH_REDDIT_LIST_SUCCESS,
    15. data: res.data
    16. });
    17. },
    18. err => {
    19. dispatch({
    20. type: FETCH_REDDIT_LIST_FAILURE,
    21. data: {error:err}
    22. }
    23. );
    24. }
    25. );
    26. };
    27. return promise;
    28. }
    29. // redux reducer
    30. export function reducer(state, action){
    31. switch (action.type){
    32. case FETCH_REDDIT_LIST_BEGIN:
    33. return (data:[action.res.data], fetchRebbitListPending: true, fetchRebbitListError:null);
    34. case FETCH_REDDIT_LIST_SUCCESS:
    35. return (...state, fetchRebbditListPending: false, fetchRebbitListError:null);
    36. case FETCH_REDDIT_LIST_ERROR:
    37. return (...state, fetchRebbitListPending: false,
    38. fetchRebbitListError:action.data.error);
    39. }
    40. }
    41. // REDUX STORE,指定middle
    42. const store = createStore(reducer, applyMiddleware(thunk));
    43. <div>
    44. <button onClick = {fetchRedditList}>获取文章列表button>
    45. {initialState.fetchRebbitListError && <span>获取文章列表失败span>}
    46. {initialState.fetchRebbditListPending && <span>加载中span>}
    47. {initialState.data
    48. &&
    49. <ul>
    50. initialState.data.map(item -> <li>item.title
    51. ul>
    52. }
    53. div>

  • 相关阅读:
    pandas函数和方法
    VMWare Vcenter Server克隆虚拟机所用端口
    NIO之Selector执行流程
    【单目标优化求解】粒子群混沌混合蝴蝶优化算法求解最优目标问题(HPSOBOA)【含Matlab源码 1538期】
    ssm+vue的OA办公系统(有报告)。Javaee项目,ssm vue前后端分离项目。
    uniapp前端样式
    狄克斯特拉算法求最短路径
    Spring MVC:文件的上传与下载
    restful定义
    windows实用功能快捷入口
  • 原文地址:https://blog.csdn.net/qq_37011724/article/details/134561383