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();
}