javascript 错误:无法从源解析图像URL(未定义)SANITY

fiei3ece  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(109)

这是我尝试打开产品

时遇到的错误
基本上它说,它不能呈现一个图像的URL,我试图从健全的数据库,但在教程中,我正在看的是他的工作很好.我的问题是,有没有一种方法来修复这个错误,我得到,因为这是我第一次与这个错误,我很困惑这里是我的代码:

import React, { useState } from 'react';

import { client, urlFor } from '../../lib/client';

const ProductDetails = ({ product, products }) => {
  const { image, name, details, price } = product ?? {};

  return (
    <div>
      <div className="product-detail-container">
        <div>
          <div className="image-container">
            <img src={urlFor(image && image[0])} />
          </div>
          <div className="small-images-container">
            {image?.map((item, i) => (
              <img
              src={urlFor(item)}
              className=""
              onMouseEnter=""
              />
            ))}
          </div>
        </div>
      </div>
    </div>
  )
}

export const getStaticPaths = async () => {
  const query = `*[_type == "product"] {
    slug {
      current
    }
  }
  `;

  const products = await client.fetch(query);

  const paths = products.map((product) => ({
    params: { 
      slug: product.slug.current
    }
  }));

  return {
    paths,
    fallback: 'blocking'
  }
}

export const getStaticProps = async ({ params: { slug }}) => {
  const query = `*[_type == "product" && slug.current == '${slug}'][0]`;
  const productsQuery = '*[_type == "product"]'
  
  const product = await client.fetch(query);
  const products = await client.fetch(productsQuery);

  console.log(product);

  return {
    props: { products, product }
  }
}

export default ProductDetails
6tdlim6h

6tdlim6h1#

您需要在urlFor调用上添加url()方法:

{image?.map((item, i) => (
  <img
  src={urlFor(item).url()}
  className=""
  onMouseEnter=""
  />
))}

此外,正如注解中所述,过滤image数组中任何可能的undefined值也是一个好主意。

相关问题