代码之家  ›  专栏  ›  技术社区  ›  juliano.net

在Typescript中使用createAsyncThunk时发生代码错误

  •  0
  • juliano.net  · 技术社区  · 4 年前

    我试图使用Typescript创建一个反应应用程序,在发生了一系列错误后,我开始后悔这个决定,哈哈。这比使用JS/Babel要冗长得多。

    但让我们来看看真正的问题。我创建了这个自定义钩子:

    useGetDeviceById.ts

    import { useEffect } from 'react';
    import { useHistory, useParams } from 'react-router-dom';
    import { useAppDispatch, useAppSelector } from 'src/hooks';
    import { fetchStatus } from 'src/shared/constants';
    import { getDeviceById } from 'src/features/device/redux/deviceOperations';
    import { getDevice, getDeviceFetchError } from 'src/features/device/redux/deviceSelectors';
    
    const useGetDeviceById = () => {
      const dispatch = useAppDispatch();
      const { push } = useHistory();
      const { deviceId } = useParams<{deviceId?: string}>();
    
      const device = useAppSelector(getDevice);
      const hasGetError = useAppSelector(getDeviceFetchError);
      const isDeviceLoading = device.fetchStatus.getProposalById !== fetchStatus.fulfilled;
      
      useEffect(() => {
        if (hasGetError) push('/');
        else {
          dispatch(getDeviceById(deviceId));
        }
      }, [push, hasGetError, dispatch, deviceId]);
    
      return { device: { ...device, deviceId }, isDeviceLoading}
    };
    
    export default useGetDeviceById;;
    

    设备操作s.ts

    import { createAsyncThunk } from '@reduxjs/toolkit';
    import { loaderActions } from '../../../features/loader/redux';
    import deviceManager from '../deviceManager';
    
    export const getDeviceById = createAsyncThunk(
      'device/GET_DEVICE_BY_ID',
      async (deviceId: number, { dispatch }) => {
        dispatch(loaderActions.start('getDeviceById'));
        try {
          const device = await deviceManager.getDeviceById(deviceId);
          return { ...device, deviceId };
        } finally {
          dispatch(loaderActions.stop('getDeviceById'));
        }
      }
    );
    

    我得到了下面的错误 dispatch(getDeviceById(deviceId)); :

    Argument of type 'AsyncThunkAction<any, number, {}>' is not assignable to parameter of type 'AnyAction'.
      Property 'type' is missing in type 'AsyncThunkAction<any, number, {}>' but required in type 'AnyAction'.  TS2345
    
        18 |     if (hasGetError) push('/');
        19 |     else {
      > 20 |       dispatch(getDeviceById(deviceId));
           |                ^
        21 |     }
        22 |   }, [push, hasGetError, dispatch, deviceId]);
        23 |
    

    你能帮助我吗?这是创建这些东西的正确方法吗?

    0 回复  |  直到 4 年前