在循环中渲染 prop NextJS

gijlo24d  于 2023-05-17  发布在  其他
关注(0)|答案(2)|浏览(160)

我试图在一个循环中渲染 prop (一个forEach函数),但我还没有弄清楚如何:(
这是我目前掌握的情况:

{console.log('the catalog inside the component ----->', catalog)}
{Object.keys(catalog).forEach(key => {
    return (
        <div className='flex flex-col'>
            <p className='ml-12 mt-12'>`${key}`</p>
            <div className='flex justify-center items-center flex-wrap'>
            {catalog[key].forEach(item => {
                return (
                    <Image src={`/${key}/${item}`} width={150} height={150} alt={`${item}`} onClick={enlarge} className='cursor-zoom-in m-4' />
                )
            })}
            </div>
        </div>
    )
})}
<p>{catalog.Marca1[0]}</p>

下面是目录的样子:

the catalog inside the component -----> {
  Marca1: [ 'gafas1.png', 'gafas2.png', 'gafas3.png', 'gafas4.png' ],
  Marca2: [ 'gafas1.png', 'gafas2.png', 'gafas3.png', 'gafas4.png' ],
  Marca3: [ 'gafas1.png', 'gafas2.png', 'gafas3.png', 'gafas4.png' ],
  Marca4: [ 'gafas1.png', 'gafas2.png', 'gafas3.png', 'gafas4.png' ]
}

最后一行在页面中呈现。我只是为了测试而添加的:
<p>{catalog.Marca1[0]}</p>
整个项目在这里:https://github.com/Tezcatlipoca0000/paver
我正在自学如何编码,所以我会有很多错误。任何帮助将不胜感激。提前感谢:)

polkgigr

polkgigr1#

这是因为foreach不返回值(它返回undefined):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#return_value
您必须将forEach方法更改为返回数组的map方法
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#return_value
代码:未测试,仅使用map方法修改forEach方法

{Object.keys(catalog).map(key => {
  return (
      <div className='flex flex-col'>
          <p className='ml-12 mt-12'>`${key}`</p>
          <div className='flex justify-center items-center flex-wrap'>
          {catalog[key].map(item => {
              return (
                  <img src={`/${key}/${item}`} width={150} height={150} alt={item} onClick={enlarge} className='cursor-zoom-in m-4' />
              )
          })}
          </div>
      </div>
  )
})}
a5g8bdjr

a5g8bdjr2#

Array#forEach返回undefined。使用Array#map来转换数组。

{Object.keys(catalog).map(key => (
    <div className='flex flex-col'>
        <p className='ml-12 mt-12'>`${key}`</p>
        <div className='flex justify-center items-center flex-wrap'>
        {catalog[key].map(item => (
            <Image src={`/${key}/${item}`} width={150} height={150} alt={`${item}`} onClick={enlarge} className='cursor-zoom-in m-4' />
        ))}
        </div>
    </div>
))}

相关问题