我正在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()。
渲染到 HTML 中的内容分别是
offices.map
和 offices.forEach
的结果。
Array.prototype.map
返回一组值(即每个值都是一次回调执行的结果)。在你的例子中是一个 HTML 元素数组(或者至少是类似的东西,我对 Astro 不熟悉)
Map.prototype.forEach
返回undefined
...因此没有任何东西可以渲染...