反应:如何解决错误:对象类型为"未知"?



我试图使用axios,以便从API获取数据,但响应。数据给了我"未知"的错误。不知道如何解决这个问题。任何人都可以帮助我。我用的是Typescript

这是我得到的错误:

对象类型为'unknown'.ts(2571)(参数)响应:AxiosResponse<unknown,>

interface Props {
pokemonItem: PokemonItem[];
children: React.ReactNode | React.ReactNode[];
}
export const PokemonContainer: React.FC = (props) => {
const { pokemonItem } = props;
const { name, height, weight, abilities } = pokemonItem;
const [hovered, setHovered] = React.useState(false);
const [imageLoaded, setImageLoaded] = React.useState(false);
const [pokemon, setPokemon] = React.useState([]);

const getPokemons = () => {
try {
axios
.get('https:pokeapi.co/api/v2/pokemon')
.then((response) => {
setPokemon(response.data.results.map((item) => item.name));
});
} catch (error) {
console.log(error);
}
};
React.useEffect(() => {
getPokemons();
}, []);

在另一个文件中,我定义了数据类型:

export interface PokemonItem {
id: number;
name: string;
height: string;
weight: string;
abilities: string;
image: string;
}

response类型是unknown到TS.unknown就像any一样,它可以是任何东西,但它是一个更安全的选择。TS将不允许您访问response属性,因为它不知道对象可能是什么。

你会想尝试这个,并使用它作为any

const getPokemons = () => {
try {
axios
.get('https:pokeapi.co/api/v2/pokemon')
.then((response : any) => { 
setPokemon(response.data.results.map((item) => item.name));
});
} catch (error) {
console.log(error);
}
};

我在使用Fetch时有同样的问题,我解决它的方法是:为"error"创建一个新的类型。";unknown"类型。

type ResponseData = {
id: string;
token: string;
error: string;
};
interface ErrorRes {
json: () => Promise<ResponseData>;
}
export const handleSignIn = async (
email: string,
password: string,
): Promise<ResponseData> => {
try {
const response = await fetch('https://reqres.in/api/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password }),
});
return (await response.json()) as ResponseData;
} catch (error) {
return await (error as ErrorRes).json();
}
};

如果你仍然需要一个不关闭TypeScript的Axios解决方案,它是:

export interface ErrorResponseData {
message: string
}
try {
const { data } = await axios.post('login', payload)
return data
} catch (e) {
return (e as AxiosError<Array<ErrorResponseData>>).response?.data[0].message || ERROR_SOMETHING_WENT_WRONG
}

AxiosError类型是一个泛型,它接受预期的错误响应接口。

当然,接口应该符合您期望的错误格式。在我的例子中,我总是收到一个错误数组,但我只对第一个错误感兴趣。然后我添加了一个回退错误,以防收到的错误与形状不匹配,例如网络错误。

最新更新