[英]JSX: Conditional statement within a map
I'm trying to understand how to incorporate conditional statements within JSX.我试图了解如何在 JSX 中合并条件语句。 I have an array of objects that I'm mapping to a select box.
我有一个要映射到 select 框的对象数组。 I want to exclude items that include the substring "threshold" in indicator.name.
我想排除在 indicator.name 中包含 substring“阈值”的项目。
So I can't use a ternary operator, because there's no "or" item.所以我不能使用三元运算符,因为没有“或”项。 But I can't figure out how to include an if statement within this map. Whatever I try I get an error.
但我无法弄清楚如何在此 map 中包含 if 语句。无论我尝试什么,都会出现错误。
<select defaultValue={defaultValue} onChange={e => setIndicator(e.currentTarget.value)} disabled={loading} > <option key='' value=''> Select </option> {indicatorList.map(indicator => ( <option key={indicator.name} value={indicator.name}> {indicator.label} </option> ))} </select>
you can filter then map:你可以过滤然后 map:
<select
defaultValue={defaultValue}
onChange={e => setIndicator(e.currentTarget.value)}
disabled={loading}
>
<option key='' value=''>
Select
</option>
{indicatorList.filter(indicator=>indicator.name.includes('threshold')).map(indicator => (
<option key={indicator.name} value={indicator.name}>
{indicator.label}
</option>
))}
</select>
Or return null:或返回 null:
<select
defaultValue={defaultValue}
onChange={e => setIndicator(e.currentTarget.value)}
disabled={loading}
>
<option key='' value=''>
Select
</option>
{indicatorList.map(indicator => (
indicator.name.includes('threshold')?<option key={indicator.name} value={indicator.name}>:nul
{indicator.label}
</option>
))}
</select>
I would recommend using the filter method to filter out "threshold".我建议使用 filter 方法来过滤掉“阈值”。 This would return the array you are expecting to have inside JSX
这将返回您期望在 JSX 中拥有的数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.