【问题标题】:Property 'type' is missing in type 'AsyncThunkAction<Device, number, { dispatch: Dispatch<AnyAction>; }>' but required in type 'AnyAction'类型 'AsyncThunkAction<Device, number, { dispatch: Dispatch<AnyAction>; 中缺少属性 'type' }>' 但在 'AnyAction' 类型中是必需的
【发布时间】:2021-07-30 20:09:29
【问题描述】:

我正在尝试调度一个动作(不知道它是否是正确的名称,因为我对 redux 和 redux-toolkit 真的很陌生)并且我收到了这个错误:

Argument of type 'AsyncThunkAction<Device, number, { dispatch: Dispatch<AnyAction>; }>' is not assignable to parameter of type 'AnyAction'.
  Property 'type' is missing in type 'AsyncThunkAction<Device, number, { dispatch: Dispatch<AnyAction>; }>' but required in type 'AnyAction'.  TS2345

    18 |     if (hasGetError) push('/');
    19 |     else {
  > 20 |       dispatch(getDeviceById(deviceId));
       |                ^
    21 |     }
    22 |   }, [push, hasGetError, dispatch, deviceId]);
    23 |

这是我的代码:

存储\index.ts

import { configureStore } from '@reduxjs/toolkit';
import { routerMiddleware } from 'connected-react-router/immutable';
import { createBrowserHistory } from 'history';
import thunkMiddleware from 'redux-thunk';
import createRootReducer from './reducers';

export const history = createBrowserHistory();

export const store = configureStore({
  reducer: createRootReducer(history),
  middleware: [routerMiddleware(history), thunkMiddleware],
});

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;

export type AppDispatch = typeof store.dispatch;

features\device\redux\deviceOperations.ts

import { createAsyncThunk } from '@reduxjs/toolkit';
import { AppDispatch } from 'src/store';
import { loaderActions } from '../../../features/loader/redux';
import deviceManager from '../deviceManager';

export const getDeviceById = createAsyncThunk<
  Device,
  number,
  {
    dispatch: AppDispatch;
  }
>('device/GET_DEVICE_BY_ID', async (deviceId: number, thunkApi) => {
  thunkApi.dispatch(loaderActions.start('getDeviceById'));
  try {
    const device = await deviceManager.getDeviceById(deviceId);
    return { ...device, deviceId };
  } finally {
    thunkApi.dispatch(loaderActions.stop('getDeviceById'));
  }
});

interface Device {
  deviceId: number;
  name: string;
}

导致这个错误的部分似乎是一个自定义钩子(我正在关注另一个项目,但我真的不明白为什么我需要这个自定义钩子以及如何在我的组件中使用它,我真的按照例子)。

功能\设备\挂钩\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)); // ERROR
    }
  }, [push, hasGetError, dispatch, deviceId]);

  return { device: { ...device, deviceId }, isDeviceLoading };
};

export default useGetDeviceById;

我该如何解决?如果我问的不多,为什么我真的需要这个自定义钩子?

【问题讨论】:

    标签: reactjs typescript redux redux-toolkit


    【解决方案1】:

    您遇到的问题是因为您覆盖了 redux-toolkit 通常应用的中间件,该中间件正确设置了类型定义。

    您可以使用getDefaultMiddleware 解决此问题,这将允许您连接已连接的路由器中间件,而不会破坏设置。

    import { configureStore } from "@reduxjs/toolkit";
    import { routerMiddleware } from "connected-react-router/immutable";
    import { createBrowserHistory } from "history";
    import createRootReducer from "./reducers";
    
    export const history = createBrowserHistory();
    
    export const store = configureStore({
      reducer: createRootReducer(history),
      middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware().concat(routerMiddleware(history))
    });
    
    // Infer the `RootState` and `AppDispatch` types from the store itself
    export type RootState = ReturnType<typeof store.getState>;
    
    export type AppDispatch = typeof store.dispatch;
    
    

    这是代码的近似值(至少足以显示/修复这些类型错误):

    https://codesandbox.io/s/strange-taussig-oweoj?file=/src/useGetDeviceById.ts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-19
      • 2019-09-15
      • 2020-11-13
      • 2020-06-16
      • 1970-01-01
      • 2021-02-23
      • 2021-11-18
      • 2020-09-30
      相关资源
      最近更新 更多