我尝试在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[]“上不存在”
1条答案
按热度按时间qrjkbowd1#
函数
getMeal
的return
值是state
的meal
属性的值,因为getMeal
函数应该返回string[]
类型的数据,根据您得到的错误,这里不是这种情况我的建议是: