用React Hook完成Strapi API呼叫

发布于 2025-01-25 16:47:35 字数 3700 浏览 0 评论 0原文

配置了Strapi以检索简单的产品列表。尝试编码React Hook以获取所有产品,然后使用Productitem组件渲染。当我使用usequery()挂钩时,我会收到以下错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'map')

这是访问strapi的挂钩函数:

export default function ProductList() {
  const { data: products, isLoading } = useQuery('Products', () => 
    axios('/api/products').then((res) => res.data.products)
  );

  if (isLoading) return <LoadingSpinner />

  return products.map((product) => (
    <ProductItem key={product.id} product={product} /> 
  ));
}

这是用于渲染和布局每个条目的布局组件:

function ProductItem({ product }) {
  const price = formatProductPrice(product);

  return (
    <div className="p-4 md:w-1/3">
      <div className="h-full border-2 border-gray-800 rounded-lg overflow-hidden">
        <Link to={`/${product.id}`}>
          <img 
            className="lg:h-96 md:h-36 w-full object-cover object-center"
            src={product.image}
            alt={product.name}
          />
        </Link>
        <div className="p-6">
          <h2 className="tracking-widest text-xs title-font font-medium text-gray-500 mb-1">
            {product.category}
          </h2>
          <h1 className="title-font text-lg font-medium text-white mb-3">
            {product.name}
          </h1>
          <p className="leading-relaxed mb-3">{product.description}</p>
          <div className="flex items-center flex-wrap ">
            <Link to={`/${product.id}`} className="text-indigo-400 inline-flex items-center md:mb-2 lg:mb-0">
              See More
              <svg
                fill="none"
                stroke="currentColor"
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth="2"
                className="w-4 h-4 ml-2"
                viewBox="0 0 24 24"
              >
                <path d="M5 12h14M12 5l7 7-7 7"></path>
              </svg>
            </Link>
            <span className="text-gray-500 mr-3 inline-flex items-center lg:ml-auto md:ml-0 ml-auto leading-none text-lg pr-3 py-1 border-gray-800 font-bold">
              {price}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}

我已经测试了,我将数据回到对象中,因此数据在那里。我认为我没有正确访问对象或一个多元化问题?不知道我在做什么错。我正在通过package.json.json的代理正确访问strapi API,

"proxy": "http://localhost:1337"

如果我直接使用https:// localhost:1337/api/products直接击中API。工作,我恢复了json的好处。我认为它必须在React Hook中。

有人看到我在用.map()的挂钩代码中做错了什么?我假设Strapi会自动分配ID字段,并通过响应发送回。

JSON从Strapi收到:

data: [{id: 1, attributes: {name: "The Contemplation of Union",…}},…],…}
data: [{id: 1, attributes: {name: "The Contemplation of Union",…}},…]
    0: {id: 1, attributes: {name: "The Contemplation of Union",…}}
    attributes: {name: "The Contemplation of Union",…}
    createdAt: "2022-05-01T02:07:51.795Z"
    description_long: "The graphite pencil work that started it 
    all.  Captured second place at the prestigious Brownlee O. 
    Curry Art Competition."
    name: "The Contemplation of Union"
    price: 399
    publishedAt: "2022-05-01T02:07:54.189Z"
    updatedAt: "2022-05-01T02:07:54.191Z"
    id: 1
1: {id: 2, attributes: {name: "Homage to Dali",…}}
2: {id: 3, attributes: {name: "Still Life with Melon",…}}
meta: {pagination: {page: 1, pageSize: 25, pageCount: 1, total: 3}}
pagination: {page: 1, pageSize: 25, pageCount: 1, total: 3}

configured Strapi to retrieve a simple list of products. Trying to code the React hook to grab all the products and then render with the ProductItem component for each item. When I use the useQuery() hook, I am getting the following error:

Uncaught TypeError: Cannot read properties of undefined (reading 'map')

Here is the hook function accessing Strapi:

export default function ProductList() {
  const { data: products, isLoading } = useQuery('Products', () => 
    axios('/api/products').then((res) => res.data.products)
  );

  if (isLoading) return <LoadingSpinner />

  return products.map((product) => (
    <ProductItem key={product.id} product={product} /> 
  ));
}

And here is the layout component that is used to render and layout each entry:

function ProductItem({ product }) {
  const price = formatProductPrice(product);

  return (
    <div className="p-4 md:w-1/3">
      <div className="h-full border-2 border-gray-800 rounded-lg overflow-hidden">
        <Link to={`/${product.id}`}>
          <img 
            className="lg:h-96 md:h-36 w-full object-cover object-center"
            src={product.image}
            alt={product.name}
          />
        </Link>
        <div className="p-6">
          <h2 className="tracking-widest text-xs title-font font-medium text-gray-500 mb-1">
            {product.category}
          </h2>
          <h1 className="title-font text-lg font-medium text-white mb-3">
            {product.name}
          </h1>
          <p className="leading-relaxed mb-3">{product.description}</p>
          <div className="flex items-center flex-wrap ">
            <Link to={`/${product.id}`} className="text-indigo-400 inline-flex items-center md:mb-2 lg:mb-0">
              See More
              <svg
                fill="none"
                stroke="currentColor"
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth="2"
                className="w-4 h-4 ml-2"
                viewBox="0 0 24 24"
              >
                <path d="M5 12h14M12 5l7 7-7 7"></path>
              </svg>
            </Link>
            <span className="text-gray-500 mr-3 inline-flex items-center lg:ml-auto md:ml-0 ml-auto leading-none text-lg pr-3 py-1 border-gray-800 font-bold">
              {price}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}

I have tested, and I am receiving the data back in the object, so the data is there. I don't think I am accessing the object correctly or perhaps a plurality issue? Not sure what I am doing wrong. I am accessing the strapi api correctly through the proxy in package.json like so:

"proxy": "http://localhost:1337"

If I hit the API directly with https://localhost:1337/api/products it works and I get back the JSON fine. It has to be in the React hook I think.

Anyone see what I am doing wrong in the hook code with the .map() ? I am assuming that Strapi automatically assigns the id field and sends it back with the response.

JSON received from Strapi:

data: [{id: 1, attributes: {name: "The Contemplation of Union",…}},…],…}
data: [{id: 1, attributes: {name: "The Contemplation of Union",…}},…]
    0: {id: 1, attributes: {name: "The Contemplation of Union",…}}
    attributes: {name: "The Contemplation of Union",…}
    createdAt: "2022-05-01T02:07:51.795Z"
    description_long: "The graphite pencil work that started it 
    all.  Captured second place at the prestigious Brownlee O. 
    Curry Art Competition."
    name: "The Contemplation of Union"
    price: 399
    publishedAt: "2022-05-01T02:07:54.189Z"
    updatedAt: "2022-05-01T02:07:54.191Z"
    id: 1
1: {id: 2, attributes: {name: "Homage to Dali",…}}
2: {id: 3, attributes: {name: "Still Life with Melon",…}}
meta: {pagination: {page: 1, pageSize: 25, pageCount: 1, total: 3}}
pagination: {page: 1, pageSize: 25, pageCount: 1, total: 3}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文