简体   繁体   English

React+Typescript 条件渲染

[英]React+Typescript conditional rendering

I want to create an option for every single profile that I have.我想为我拥有的每个个人资料创建一个选项。 I checked and I do have a profile so the profiles array is not empty and profile.profilename isn't undefined.我检查了,我确实有一个配置文件,所以配置文件数组不是空的,并且 profile.profilename 不是未定义的。 It just doesn't render.它只是不渲染。

What i see: Picture我看到了什么:图片

<div className="col-4">
   <select name="profile" className="billingSelector">
         <option>Billing profile</option>
             {(getProfiles() as any).forEach((profile:Profile) => {
                  <option>{profile.profileName}</option>
              })}
   </select>
</div>

I found a solution.我找到了解决方案。 I used map instead of foreach and i removed curly braces and used regular ones.我使用 map 而不是 foreach 并且我删除了花括号并使用了普通的。

<select name="profile" className="billingSelector">
   <option>Billing profile</option>
   {getProfiles().map((profile:Profile)=> (
        <option key={profile.profileName}>{profile.profileName}</option>
   ))}       
</select>

Use map instead of foreach .使用map而不是foreach

There is a difference.它们是有区别的。 Map returns list, foreach - not. Map 返回列表,foreach - 不是。

More info on that:更多信息:

Array.prototype.forEach() - JavaScript | Array.prototype.forEach() - JavaScript | MDN MDN

Array.prototype.map() - JavaScript | Array.prototype.map() - JavaScript | MDN MDN

Instead of foreach can you please try map?代替 foreach 你可以试试 map 吗? Eg例如

getProfiles().map((profile, index) => ( {profile.profileName})); getProfiles().map((profile, index) => ({profile.profileName}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM