我正在尝试使用 Typescript 创建一个 React 应用程序,并且在一系列错误之后开始对这个决定感到遗憾,哈哈。它比使用 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;;
deviceOperations.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 |
你能帮我吗?这是创建这些东西的正确方法吗?