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
        }))
    }
}
posted @ 2022-12-10 22:30  HuangBingQuan  阅读(236)  评论(0编辑  收藏  举报