如何映射从 api 获取的数据?

问题描述 投票:0回答:1

基本上,我有一个搜索页面组件,它显示用户在输入字段中键入的查询的搜索结果。

这是文件。

"use client";

import { useSearchParams } from "next/navigation";
import useFetch from "../hooks/useFetch";
import ProductCard from "@/components/ProductCard";

const SearchPage = () => {
  const search = useSearchParams();
  const searchQuery = search ? search?.get("q") : null;
  const encodedSearchQuery = encodeURI(searchQuery || "");

  const { data } = useFetch(
    `/products?populate*=&filters[title][$contains]=${encodedSearchQuery}`
  );
  console.log(data);

  return (
    <div>
      <div>
         {/* {data?.map((product) => (
          <ProductCard key={product.id} products={product} />
        ))} */}
      </div>
    </div>
  );
};

export default SearchPage;

我正在使用全局钩子 useFetch 。 我也可以在控制台中看到过滤后的数据。 Productcard 组件基本上用于结构,它需要一个名为 products 的道具

我尝试使用注释掉的代码进行映射,但它向我显示了这些错误。

这是 useFetch.tsx

在此代码片段中,我有一个名为 fetchData 的实用函数,它负责发出 API 请求。它使用 Axios 发出请求并包含授权标头。

"use client";

import { useState, useEffect } from "react";
import { fetchData } from "@/app/utils/api";

const useFetch = (endpoint: string) => {
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchDataFromApi = async () => {
      try {
        const res = await fetchData(endpoint);
        setData(res);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };

    fetchDataFromApi();
  }, [endpoint]);

  return { data };
};

export default useFetch;

类型“never”上不存在属性“map”。 参数“product”隐式具有“any”类型。

我实际上看到有人以完全相同的方式做到了这一点,但是使用了 Javascript。 我正在使用打字稿,我对它很陌生。我应该如何用打字稿来做?

如果有人想看的话,我可以展示更多与之相关的组件。

如有任何帮助,我们将不胜感激

reactjs typescript next.js next
1个回答
0
投票

您需要声明预期类型(例如:Product)并将其传递给 TypeScript,并使

useFetch
泛型化(获取返回的预期数据类型):

// types.ts
export interface Product {
  // replace with the actual data structure
  id: string
  name: string
  description: string
  price: number
  currency: 'USD' | 'EUR'
  // etc...
}
// useFetch.ts
function useFetch<T>(endpoint: string): { data: T[] } {
  const [data, setData] = useState<T[]>([]);

  // ... actual fetching and setting to `data`

  return { data }
}
// in any component:
import { Product } from './path/to/types'
import { useFetch } from './path/to/useFetch'

const { data } = useFetch<Product>(
  `/products?populate*=&filters[title][$contains]=${encodedSearchQuery}`
)

现在

data
将输入为
Product[]

很明显,您必须修改

Product
界面以满足您的需求。作为旁注,它也可以是
type

© www.soinside.com 2019 - 2024. All rights reserved.