React 18 仿携程项目【二十二】redux-thunk中间件实现异步action

redux-thunk中间件用来实现Redux异步处理

作用:可通过异步action把请求网络api从组件中剥离出来实现复用!!

安装redux-thunk

npm install redux-thunk@2.4.1

在store.ts中对应的功能模块productRecommendAction中引入thunk类型、RootState 和axios

productRecommendAction.ts

import { ThunkAction } from "redux-thunk";
import { RootState } from '../store';
import axios from 'axios';
//axios获取api数据
export const  FetchDataActionCreator = ():ThunkAction<
void, //内层函数的返回值类型
RootState, //store类型
unknown, //定义action中额外参数类型
productRecommendActionTypes //组件的action类型
>=> 
async (dispatch,getState)=>{ //传入dispatch和getState2个参数
    dispatch(productRecommendStartActionCreator());
    try {
        const res = await axios.get("http://123.56.149.216:8080/api/productCollections")
        dispatch(productRecommendSuccessActionCreator(res.data));//请求成功时发送数据
    } catch (error) {
        // if (error instanceof Error) { 
        //     dispatch(productRecommendFailActionCreator(error.message))
        // }
        //等同于以下写法
        dispatch( //请求失败发送报错信息
            productRecommendFailActionCreator(error instanceof Error ? error.message : "error")
        )
    }
} 

然后在类组件中使用

homePage.ts

import { RootState } from "../../redux/store";
import { FetchDataActionCreator } from "../../redux/productRecommend/productRecommendActions"

 然后mapDispatchToProps 映射数据后写法:

//定义映射数据类型
type  propsType = ReturnType<typeof mapStateToProps> & 
ReturnType<typeof mapDispatchToProps>

const mapDispatchToProps = (dispatch) => {
    return {
        giveMeData: ()=>{
            dispatch(FetchDataActionCreator())
        }
    }
}

最终在组件的componentDidMount中使用请求到的数据:

componentDidMount() {
     this.props.giveMeData();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值