【发布时间】:2021-02-21 07:30:06
【问题描述】:
我正在构建一个示例 Web 应用程序并使用 this dummy data api 来获取数据。我正在使用带有 axios 的 React 进行 api 调用。响应数据如下所示
所以我创建了以下接口来表示数据。
export type Category = {
id: number,
name: string
}
export type Product = {
id: number,
name: string,
description: string,
image: string,
price: number,
discount_amount: number,
status: boolean,
categories: Array<Category>
}
export type ProductResponse = {
data: {
code: number,
data: Array<Product>
}
}
我正在按照以下方式获取数据并存储在类型化的状态变量中
const [products, setProducts] = useState<Array<Product>>([]);
const fetchProducts = (): void => {
const productUrl = "https://gorest.co.in/public-api/products";
axios.get<ProductResponse>(productUrl).then((res) => {
setProducts(res.data.data);
});
};
useEffect(() => {
fetchProducts();
}, []);
类型错误
/home/ravinda/myjunkbox/react/react-redux-cake-shop-ts/src/components/Products.tsx
TypeScript error in /home/ravinda/myjunkbox/react/react-redux-cake-shop-ts/src/components/Products.tsx(12,19):
Argument of type '{ code: number; data: Product[]; }' is not assignable to parameter of type 'SetStateAction<Product[]>'.
Type '{ code: number; data: Product[]; }' is not assignable to type '(prevState: Product[]) => Product[]'.
Type '{ code: number; data: Product[]; }' provides no match for the signature '(prevState: Product[]): Product[]'. TS2345
10 | const productUrl = "https://gorest.co.in/public-api/products";
11 | axios.get<ProductResponse>(productUrl).then((res) => {
> 12 | setProducts(res.data.data);
| ^
13 | });
14 | };
15 |
我想我正在尝试从响应中提取产品数组并设置为状态变量。我在这里做错了什么?
【问题讨论】:
标签: reactjs typescript axios