欢迎来到码农权的博客 MaNongGeGe.|

redux-thunk与redux-promise

redux-thunk与redux-promise

  • redux-thunk与redux-promise都是一个中间件,目的:用来处理redux中的复杂逻辑,比如异步请求;

redux-thunk

  • 用法:
  • store里面提供了applyMiddleware方法来在初始化store的时候加载中间件
  //action生成器中的代码
  export const asyncAdd = ()=> {
    // 异步操作的返回的是一个函数,该函数可以接收一个dispatch函数(其实就是redux仓库暴露出的dispatch派发函数)
    return (dispatch)=> {
      setTimeout(()=> {
        dispatch({
          type: 'handel-add',
          payload: { xxx, xxx} // 接口返回的数据
        })
      }, 100)
    }
  }
  • 中间件概念并不复杂,它的出现时为了方便我们在Action执行之前可以插入一些操作或者新的功能,比如日志统计,信息打印,异步操作等等。
  • 先看一下没有加中间件的时候redux的流程:

redux-promise

  1. 初始化 yarn add redux-promise
  2. 引入应用中间件 import { createStore, applyMiddleware } from "redux";
  3. 应用中间件 const store = createStore(reducer, applyMiddeware(reduxPromise))
  • redux-promise的几种使用方法,以下都是在action生成器中的使用场景:
// * 直接返回一个promise
export function fetchStudents() {
    return new Promise(resolve => {
        setTimeout(() => {
            const action = setStudentAndTotal([{ id: 1, name: 'zc' }, { id: 2, name: 'gg' }],100)
            resolve(action);
        },1000)
    })
}


// 结合async await使用
export async function fetchStudents(condition) {
    const resp = await searchStudents(condition)
    return setStudentAndTotal(resp.datas, resp.cont);
}

// payload接收一个promise
export async function fetchStudents(condition) {
    return {
        type: actionTypes.setStudentAndTotal, 
        payload: await searchStudents(condition).then(resp => ({
            datas: resp.datas,
            total: resp.cont
        }))
    }
}

本文作者:HuangBingQuan

本文链接:https://www.cnblogs.com/bingquan1/p/16972491.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   HuangBingQuan  阅读(265)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 不将就 码农权
  2. 2 Bleeding Love 码农权
  3. 3 想你念你 码农权
Bleeding Love - 码农权
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

Not available