我试图迭代javascript Set()在React组件内的props中传递下来。我无法在屏幕上渲染任何迭代:
{selectedCity.forEach((key, value) => (
return (
<Row>
<Col sm={12} md={6} mdOffset={4} lgOffset={4}>
<Typography className="hide-mobile" h3>
TICKET PRICE FOR IN-STATE:
</Typography>
<Typography h3>{value.name}</Typography>
<TicketPriceInput
onChange={e => {
setConcertDetails('price', e.target.value);
detectInputChange(e);
}}
value={price}
name="price"
isPriceChanged={isPriceChanged}
/>
<OutPriceLabel className="hide-mobile">
<Typography h3>TICKET PRICE FOR OUT-OF-STATE:</Typography>
<Typography h3 bold className="hide-mobile">
{outLocationPrice()}
</Typography>
</OutPriceLabel>
<FootNote>
<Typography medium spaced className="hide-mobile">
*After the first 20 tickets anyone located in-state can
purchase tickets at the regular ticket price you set.
</Typography>
</FootNote>
</Col>
</Row>
);
))}
我已经用map()
或Object.keys()
的数组或对象做过很多次了,它工作了。
您必须使用map
。这是因为map
将返回组件,但forEach
不会。map
是一个数组方法,在set中不可用。但是你可以通过使用Array.from(它会将Set
转换为Array
)来轻松地映射集合
Array.from(selectedCity).map(...)
Set.forEach()
方法迭代Set的值,但不像其他.forEach()
方法那样返回。
一个选项是将创建的元素压入数组,然后返回数组:
const renderSelectedCity = selectedSet => {
const rendered = [];
selectedSet.forEach(value => {
rendered.push(
<Row key={value.id}>
// your JSX
</Row>
);
});
return rendered;
};
然后你可以通过调用函数来使用它,并提供Set:
{renderSelectedCity(selectedCity)}
另一种选择是将Set扩展到一个数组,使用Array.map()
迭代该数组,这将返回一个呈现元素的新数组:
{[...selectedCity].map(value => (
<Row key={value.id}>
// your JSX
</Row>
))}
您也可以使用Array.from()
从Set
创建一个JSX数组:
Array.from(selectedCity, value => (
<Row key={value.id}>
// your JSX
</Row>
))}