[英]Iteration over Set in React component won't render in JSX
我正在嘗試迭代在 React 組件內的道具中傳遞的 javascript Set()。 迭代到位后,我無法在屏幕上呈現任何內容:
{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>
);
))}
我已經用 Array 或 Object 和map()
或Object.keys()
完成了很多次,並且成功了。
您必須使用map
。 那是因為map
將返回組件,但forEach
不會。 map
是一種數組方法,在 Sets 中不可用。 但是您可以使用 Array.from 輕松地在集合上map (這會將Set
轉換為Array
)
Array.from(selectedCity).map(...)
Set.forEach()
方法不會迭代 Set 的值,但不會像其他.forEach()
方法一樣返回。
一種選擇是將創建的元素推送到數組,然后返回數組:
const renderSelectedCity = selectedSet => {
const rendered = [];
selectedSet.forEach((key, value) => {
rendered.push(
<Row>
// your JSX
</Row>
);
});
return rendered;
};
然后您可以通過調用 function 並提供 Set 來使用它:
{renderSelectedCity(selectedCity)}
另一種選擇是將 Set 傳播到一個數組,使用Array.map()
迭代數組,這將返回一個新的渲染元素數組:
{[...selectedCity].map((key, value) => (
<Row>
// your JSX
</Row>
))}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.