reactjs 设置对象数组的类型和接口时出错

4zcjmb1e  于 2022-11-04  发布在  React
关注(0)|答案(1)|浏览(141)

使用扩展运算符创建了一个新的对象数组。
我试图用一个map来通过这个,但是我认为类型的定义不对。
我想看看redux工具包的react代码,接口PostState部分的定义似乎是无效的。但我不知道如何解决它
使用redux工具包,在加载类别后,使用spread操作符将数据放入新的数组中。

数据

要实现的代码

{cartegory && cartegory.map((value, index) => {
       return (
           <Tab label={value.snippet.title} {...a11yProps(index)} key={value.id} />
       )
 })}

问题

类型'{}'上不存在属性'snippet'。TS 2339

类型脚本类型

export type cartegory = {
    kind: string
    etag: string
    id: string
    snippet: {
        publishedAt: string
        channelId: string
        title: string
        description: string
        thumbnails: {
            default: {
                url: string
                width: number
                height: number
            }
            medium: {
                url: string,
                width: number,
                height: number
            }
            high: {
                url: string,
                width: number,
                height: number
            }
            standard: {
                url: string,
                width: number,
                height: number
            }
            maxres: {
                url: string,
                width: number,
                height: number
            }
        }
        channelTitle: string,
        playlistId: string,
        position: 0
        resourceId: {
            kind: string,
            videoId: string
        }
        videoOwnerChannelTitle: string
        videoOwnerChannelId: string
    }
}[]

redux工具包响应ts代码

import type { PayloadAction } from "@reduxjs/toolkit";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";
import { youTubeAcsses } from '../apis/keys';
import { youtubeResponse, cartegory } from "../getTypes";

interface PostState {
    loading: boolean;
    error: string | null;
    data: youtubeResponse | null;
    cartegory: cartegory | {}[]
}

const initialState = {
    loading: false,
    error: null,
    data: null,
    cartegory : []
} as PostState;

// ACTION
export const youtubeList_Playlist = createAsyncThunk(
    "GET/YOUTUBE_CHANNELID",
    async (channelId: string, thunkAPI) => {
        try {
            const { data } = await axios.get<youtubeResponse>(
                `https://www.googleapis.com/youtube/v3/playlists?key=${youTubeAcsses.apiKey}&channelId=${channelId}&part=snippet&maxResults=30`
                // channelId=UCvpIHsNLXfpOj_uMgI62I2A - 그리곰 픽쳐스 상업 유튜브 채널
            )
            return data
        } catch (err: any) {
            return thunkAPI.rejectWithValue({
                errorMessage: '호출에 실패했습니다.'
            })
        }
    }
);

// SLICE
const youtube_PlaylistSlice = createSlice({
    name: "YOUTUBE_PLAYLIST",
    initialState,
    reducers: {},
    // createAsyncThunk 호출 처리 = extraReducers
    extraReducers(builder) {
        builder
            .addCase(youtubeList_Playlist.pending, (state, action) => {
                state.loading = true;
            })
            .addCase(youtubeList_Playlist.fulfilled, (state, action: PayloadAction<youtubeResponse>) => {
                state.loading = false;
                state.data = action.payload;
                state.cartegory = [...state.data.items, ...action.payload.items]
            })
            .addCase(youtubeList_Playlist.rejected, (state, action: PayloadAction<any>) => {
                state.error = action.payload;
            });
    },
});

export default youtube_PlaylistSlice.reducer;

请给予我一些建议

3htmauhk

3htmauhk1#

interface PostState {
    loading: boolean;
    error: string | null;
    data: youtubeResponse | null;
    cartegory: cartegory | {}[] // <-- here
}

这个类型是cartegory | {}[],这意味着值可以是cartegory,也可以是一个空对象数组,而这些空对象没有snippet属性.
您可以删除该| {}[],使其变得简单:

interface PostState {
    loading: boolean;
    error: string | null;
    data: youtubeResponse | null;
    cartegory: cartegory // <-- here
}

或者,您也可以在存取属性之前先检查属性是否存在。

{cartegory && cartegory.map((value, index) => {
            if ('snippet' in value) {
                return (
                    <Tab label={value.snippet.title} {...a11yProps(index)} key={value.id} />
                )
            }
            return null
        })}

相关问题