我正在呼叫 Axios 來獲取資料。Axios 呼叫的型別應該是什么?現在,型別是 any 但我怎樣才能使它更嚴格?
import axios from "axios";
import { createContext, useEffect, useContext, useReducer } from "react";
import { Action, LevelsType, State, StateContextType, StateProviderPropsType } from "../Types/types";
const LevelCtx = createContext({} as StateContextType);
export function LevelProvider({children}:StateProviderPropsType) {
const initialState:State = {
levels: null
}
const [state, dispatch] = useReducer(reducer, initialState)
useEffect(() => {
(async () => {
const response = await axios.get<any>("http://localhost:5000/levels"); // Fix required.
return dispatch({type: "SET_LEVELS", payload: response.data.levels})
})();
}, [])
function reducer(state:State, action: Action) {
switch (action.type) {
case "SET_LEVELS":
return {...state, levels: action.payload }
default:
return state
}
}
console.log("levelCTX", state);
return (
<LevelCtx.Provider value={{ state, dispatch }}>
{children}
</LevelCtx.Provider>
)
};
export function useLevelCtx() {
return useContext(LevelCtx);
}
我的型別檔案看起來像這樣 -
import { ReactNode }from "react";
export type LevelsObjectType = {
_id: string;
img: string;
levelName: string;
__v: number;
}
export type LevelsType = {
levels: LevelsObjectType[]
}
export type State = {
levels: LevelsType[] | null;
}
export type StateProviderPropsType = {
children: ReactNode;
}
export type StateContextType = {
state: State;
dispatch: React.Dispatch<Action>;
}
export type Action =
| { type: "SET_LEVELS"; payload: LevelsType[] }
export type ServerError = {
errorMessage: string;
}
我從 api 呼叫中獲得的資料是這樣的 -

現在,當我嘗試映射 state.levels 時,執行此操作后,它會引發以下錯誤 -

我嘗試將 LevelsType 添加到上述 axios 呼叫中,但它引發了錯誤。我正在嘗試使用 React TS 設定 useRecuder 和 useContext。我是打字稿的新手。所以請幫我弄清楚這一點。
uj5u.com熱心網友回復:
你可以有兩種型別:
export type LevelsObjectType = {
_id: string;
img: string;
levelName: string;
__v: number;
}
export type LevelsObjectTypeResult = {
levelsObjects: LevelsObjectType[],
success: boolean
}
并回傳:
await axios.get<LevelsObjectTypeResult>("http://localhost:5000/levels")
在減速機中:
return {...state, levels: action.payload.levelsObjects }
uj5u.com熱心網友回復:
由于您的State型別的定義方式,您收到錯誤
export type State = {
levels: LevelsType[] | null;
}
當你這樣做時state.levels.map(level),級別型別是LevelsType你這樣定義的
export type LevelsType = {
levels: LevelsObjectType[]
}
所以你試圖訪問_id一個LevelsType物件,顯然打字稿抱怨它,因為_id它不存在于LevelsType.
試試這個:
export type State = {
levels: LevelsObjectType[] | null;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/379227.html
