【问题标题】:React typescript with axios response type使用 axios 响应类型响应 typescript
【发布时间】: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


    【解决方案1】:

    根据给出的错误,我相信您的结果缺少额外的.data。为了访问 Axios 的 response 中的值,您需要执行 .data,在您的情况下,.data 将为您提供 ProductResponse

    const fetchProducts = (): void => {
        const productUrl = "https://gorest.co.in/public-api/products";
        axios.get<ProductResponse>(productUrl).then((res) => {
          setProducts(res.data.data.data);
        });
      };
    

    res.data 应该给你ProductResponse

    res.data.data应该给你

    {
      code: number,
      data: Array<Product>
    }
    

    res.data.data.data 应该给你Array&lt;Product&gt;,与你在useState 中指定的类型相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 2019-12-09
      • 2021-05-06
      • 2019-05-12
      • 1970-01-01
      • 2021-07-26
      • 2020-10-25
      相关资源
      最近更新 更多