【react-redux bug解决】createAsyncThunk所定义的函数调用不运行

一、场景描述

错误代码1

useEffect(() => {
    console.log("开启请求");
    const res = fetchAlbumsAsync();    #这个fetchAlbumAsync()方法是createAsyncThunk定义的方法需要用dispatch来调用
    console.log(res);
}, [dispatch]);

错误代码2

const dispatch = useDispatch();   #错误处1
useEffect(() => {
    console.log("开启请求");
    const res = dispatch(fetchAlbumsAsync());   #错误处2
    console.log(res);
}, [dispatch]);

报错信息:
在这里插入图片描述
分析:这个错误的报错原因,我的理解是这个ts的类型系统定义,可能是fetchAlbumsAsync这个方法的类型跟dispatch所需要的参数类型不一致。====> useDispatch()方法想要接收的参数是UnknowAction的类型,fetchAlbumsAsync()的类型是AsyncThunkAction<any, void, AsyncThunkConfig>。
在这里插入图片描述
所以这个dispatch就是AppDispatch类型的方法,默认就是Dispatch。
在这里插入图片描述
在这里插入图片描述
输入参数类型T,返回类型也是T,T默认UnknowAction。
所以就需要定义一下这个fetchAlbumsAsync的类型。

二、解决方案

2.1 最简单的解决方案(不推荐)

  const dispatch = useDispatch<any>();    //利用any定义类型给UnknowAction赋值
  console.log(dispatch);
  useEffect(() => {
    console.log("开启请求");
    const res = dispatch(fetchAlbumsAsync());
    console.log(res);
  }, [dispatch]);

2.2 利用函数调用签名重写useDispatch()

首先我们要明白重写的原因:就是想给A extends Action赋值UnknowAction。就是定义上面这个解决方案的。

type AppDispatch = typeof store.dispatch;
export const useAppDispatch: () => AppDispatch = useDispatch;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值