NextJS 不显示来自静态 json 文件的内容

NextJS not showing content from static json file

我对 Next 比较陌生,但这就是问题所在。我有一个静态 JSON 文件,它位于我的项目目录的根目录中,如下所示

{"data":[{"id":1,"attributes":{"name":"Test Product 1","content":"Stvarno ne znam sta bi dodao ovdje jer samo testiram","meta_description":"Opis koji moze da stoji u meti / SEO i to","meta_title":"Testni Product - Lion Kingdom","price":12.99,"slug":"test-product-1","createdAt":"2022-04-17T12:12:36.787Z","updatedAt":"2022-04-17T12:12:39.540Z","publishedAt":"2022-04-17T12:12:39.531Z"}},{"id":2,"attributes":{"name":"Test Product 2","content":"Jos jedan testni post da testiram producte v2","meta_description":"Neki opis za metu","meta_title":"Testni Product 2 - Lion Kingdom","price":49700,"slug":"test-product-2","createdAt":"2022-04-17T12:15:04.241Z","updatedAt":"2022-04-17T12:15:05.078Z","publishedAt":"2022-04-17T12:15:05.075Z"}}],"meta":{"pagination":{"page":1,"pageSize":25,"pageCount":1,"total":2}}}

现在我正试图将它作为一个道具传递给在网站上使用它,但由于某些未知原因我无法做到,编译器没有显示任何错误,但 div 仍然显示为空未从 json 获取任何内容。下面是我在 next

中的设置方式

在顶部定义它

import products from '../products.json'

然后在正文中


export default function index() {
  return (
    <div>
      <Head>
      <title> ECommerce Alpha</title>
      <link rel="icon" href="/favicon.ico" />
      </Head>

    {products.data.map(product => {
      <div key={product.attributes}>
       <div>{product.attributes.name}</div>
      </div>
    })}


    </div>
  )
}

结果仍然是一个空白页,如果有人能指出为什么 next 没有从文件中静态获取它,我将不胜感激:)

您看到的是空白页,因为您的 map() 箭头函数缺少明确的 return 语句:

{products.data.map((product) => {
  // this is a block body (i.e., opened with a brace), so you need a `return`
  return (
    <div key={product.id}>
      <div>{product.attributes.name}</div>
    </div>
  );
})}

您可以通过不使用大括号使 return 隐式化:

{products.data.map((product) => (
  // group with parentheses instead
  <div key={product.id}>
    <div>{product.attributes.name}</div>
  </div>
))}