在 Astro 上创建 html 元素时,Map.prototype.forEach() 不起作用[重复]

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

我正在Astro框架上写一个小网站。我有一份“文件接受点”清单。以前,我只是将它们存储在变量

offices = [ {} , {} , {} ]
中。我将它们输出到前端,如下所示:

// Here the offices is an Array

<select size='2'>)
  { offices.map( (i) => <option value={i.id}> {i.name} </option> ) }
</select>

现在我尝试通过 Map().foreach() 做同样的事情,但没有任何效果:

// Offices.ts

const offices: Map<string, office> = new Map()

const volskaya: office = {
  id: 'volskaya',
  name: 'name',
  address: 'address',
  phone: '+x (xxx) xxx-xx-xx',
  phoneUrl: 'tel:+xxxxxxxxxxx',
  working: ''
}

const rabochaya: office = {
  id: 'rabochaya',
  name: 'name',
  address: 'address',
  phone: '+x (xxx) xxx-xx-xx',
  phoneUrl: 'tel:+xxxxxxxxxxx',
  working: ''
}

offices.set('volskaya', volskaya)
offices.set('rabochaya', rabochaya)

export {offices}


// Component.astro
---
import { offices } from "./offices";
---

<select>)
  { offices.forEach( (i) => <option value={i.id}> {i.name} </option> ) } // not working
</select>

同时,如果我将数据输出到console.log(),一切都会按预期显示:

offices.forEach((i)=> console.log(i.id,i.name)) // working

我无法理解。要么是使用 Map() 有一些限制,要么是我错误地使用了 Map()。

javascript html dictionary web-frontend
1个回答
0
投票

渲染到 HTML 中的内容分别是

offices.map
offices.forEach
的结果。

Array.prototype.map
返回一组值(即每个值都是一次回调执行的结果)。在你的例子中是一个 HTML 元素数组(或者至少是类似的东西,我对 Astro 不熟悉)

Map.prototype.forEach
返回
undefined
...因此没有任何东西可以渲染...

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