reactjs - 使用 Typescript 和 Redux Toolkit 后在 createAsyncThunk 函数中获取 'Object is of type unknown'

标签 reactjs typescript redux react-redux redux-toolkit

我在 React 应用程序中使用 Typescript,同时还使用 Redux Toolkit 进行状态管理。数据来自 Express Api,如果我在没有 Typescript 的情况下实现 Redux,一切都会完美运行,但如果我使用 Typescript,则会收到此错误:

ERROR in src/features/product/productSlice.tsx:61:27
TS2571: Object is of type 'unknown'.
     59 |         return data;
     60 |     } catch ( error ) {
   > 61 |         const message = ( error.response && error.response.data && error.response.data.message ) || error.message || error.toString();
       |                           ^^^^^
     62 |         return thunkAPI.rejectWithValue( message );
     63 |     }
     64 | } );

现在我对 Typescript 和 Redux Toolkit 都很陌生,我不知道它是如何解决这个问题的。

我只是在 thunk 函数中发出 get 请求,以在页面加载时获取数据。

这就是 productsSlice.tsx 文件的样子:

import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { RootState, AppThunk } from '../../app/store';
import getAllProducts from './productService';

interface Specifications {
    display: string,
    processor: string,
    frontCam: string,
    rearCam: string,
    ram: string,
    storage: string,
    batteryCapacity: string,
    os: string;
}

interface Products {
    title: string,
    slug: string,
    description: string,
    color: string,
    price: number,
    image: string,
    specifications: Specifications;
};

export interface Data {
    success: boolean;
    message: string;
    data: Products[] | null;
}

interface ProductState {
    products: Products[] | null,
    isError: boolean;
    isSuccess: boolean;
    isLoading: boolean;
    message: string;
}

const initialState: ProductState = {
    products: null,
    isError: false,
    isSuccess: false,
    isLoading: false,
    message: ''
};

export const getProducts = createAsyncThunk( 'products/getAllProducts', async ( _, thunkAPI ) => {
    try {
        const data = await getAllProducts();
        return data;
    } catch ( error ) {
        const message = ( error.response && error.response.data && error.response.data.message ) || error.message || error.toString();
        return thunkAPI.rejectWithValue( message );
    }
} );

export const productSlice = createSlice( {
    name: 'products',
    initialState,
    reducers: {},
    extraReducers: ( builder ) => {
        builder
            .addCase( getProducts.pending, ( state ) => {
                state.isLoading = true;
            } )
            .addCase( getProducts.fulfilled, ( state, action ) => {
                state.isLoading = false;
                state.isSuccess = true;
                state.products = action.payload.data;
            } )
            .addCase( getProducts.rejected, ( state, action ) => {
                state.isLoading = false;
                state.isError = true;
                state.message = action.payload;
                state.products = null;
            } );
    }
} );


export const getProductsSelector = ( state: RootState ) => state.products;
export default productSlice.reducer;

这是productService.tsx:

import axios from 'axios';
import { Data } from './productSlice';

const API_URL: string = '/api/phones';

const getAllProducts = async (): Promise<Data> => {
    const response = await axios.get( API_URL );
    return response.data;
};

export default getAllProducts;

这是商店:

import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import products from '../features/product/productSlice';

export const store = configureStore( {
    reducer: {
        products
    },
} );

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
    ReturnType,
    RootState,
    unknown,
    Action<string>
>;

最佳答案

在 TypeScript 中,catch block 中的所有内容都是未知 - 毕竟,上游代码可能抛出 5抛出“foo” "抛出窗口抛出未定义抛出 new Error("message") - 所以你不能保证有是error.response

如果你知道你正在等待一个类错误并且知道这个类,你就可以这样做

    } catch ( error ) {
       if (error instanceof AxiosError) {
        const message = ( error.response && error.response.data && error.response.data.message ) || error.message || error.toString();
        return thunkAPI.rejectWithValue( message );
        }
       // unhandled non-AxiosError goes here
       throw error
    }

关于reactjs - 使用 Typescript 和 Redux Toolkit 后在 createAsyncThunk 函数中获取 'Object is of type unknown',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71408918/

相关文章:

javascript - 项目显示何时应隐藏

reactjs - Ant Design for React Native 真正的原生组件?

javascript - URLSearchParams 返回空对象

javascript - React-router v4,URL 更改但组件不呈现

reactjs - 如何从对象数组映射 MUI 5 图标并更改其颜色?

typescript - 如何使用 Material UI 和 TypeScript 将自定义 Prop 传递给样式化组件?

reactjs - 重复的字符串索引签名.ts(2374)

redux - 如何使用 redux 工具包从 redux 状态的数组中删除单个元素

reactjs - 如何在 React Router v4 中操作历史记录?

javascript - react : Updated state not reflecting in recursive useCallback