Redux和Typescript“属性”prop“在类型”string[]“上不存在”

yptwkmov  于 2023-01-21  发布在  TypeScript
关注(0)|答案(1)|浏览(153)

我尝试在redux中获取数据并返回其中的一部分,而不是全部,但Typescript告诉我“Property 'xxx' does not exist on type 'string[]'”。我尝试查看它,它与接口或initialState有关,但无法找到可靠的答案。

import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axios from 'axios';
import { useAppDispatch } from './hooks';

export interface MealState {
  meal: string[],
  input: string,
  favorites: string[],
  categories: string[],
}

const initialState: MealState = {
  meal: [],
  input: '',
  favorites: [],
  categories: [],
};

const mealReducer = createSlice({
  name: 'meal',
  initialState,
  reducers: {
    // ADD INPUT
    addInput: (state, action: PayloadAction<string>) => {
      state.input = action.payload
    },

  },
  extraReducers: (builder) => {
    builder.addCase(getMeal.fulfilled, (state, action) => {
      state.meal = action.payload;
    });
  }

});

// ----------------------------------------------------------------------

export default mealReducer.reducer

// Actions
export const {
  addInput,
  addFavorites,
} = mealReducer.actions;


export const getMeal = createAsyncThunk(
  'meal/getMeal',
  async (search: string) => {
    const response = await axios.get<string[]>(`https://www.themealdb.com/api/json/v1/1/search.php?s=${search}`);
    return response.data.meals; // <== this create the problem, I can only return response.data
  }
);

我可以使用response.data,但当我使用

const list = useAppSelector((state: RootState) => state.meal.meal.meals)

因为一开始就不存在meals,所以我会得到“属性”meals“在类型”string[]“上不存在”

qrjkbowd

qrjkbowd1#

函数getMealreturn值是statemeal属性的值,因为

meal: string[]

getMeal函数应该返回string[]类型的数据,根据您得到的错误,这里不是这种情况
我的建议是:

  • console.log并更好地了解您从请求中得到的响应
  • 从响应创建常量myMeal
  • 还回去
async (search: string) => {
   const response = await axios.get<any>(`https://www.themealdb.com/api/json/v1/1/search.php?s=${search}`);
   console.log(response.data);
   const myMeal: string[] = // I don't know how your response.data looks like but myMeal should be of type string[]
   return myMeal;
  }

相关问题