【问题标题】:React+Typescript conditional renderingReact+Typescript 条件渲染
【发布时间】:2021-07-22 05:55:41
【问题描述】:

我想为我拥有的每个个人资料创建一个选项。我检查了,我确实有一个配置文件,所以配置文件数组不是空的,并且 profile.profilename 不是未定义的。它只是不渲染。

我所看到的: 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>

【问题讨论】:

  • getProfiles() 返回什么?为什么as any
  • 因为任何无关紧要,我只是想修复它。 getProfiles() 返回一个 Profile 数组,所以我得到了它的所有元素。我从代码中删除了as any
  • 它是异步的吗? console.log(getProfiles()) 打印什么?
  • console.log(getProfiles()) 打印出数组。它有一个元素,即我想在屏幕上显示的个人资料。
  • [p] 0: p {profileName: "test profile #1", firstName: "John", lastName: "Doe", postalCode: "29223", city: "Celle", …} length: 1 __proto__: Array(0)

标签: reactjs typescript conditional-statements rendering tsx


【解决方案1】:

使用map 而不是foreach

有区别。 Map 返回列表,foreach - 不是。

更多信息:

Array.prototype.forEach() - JavaScript | MDN

Array.prototype.map() - JavaScript | MDN

【讨论】:

    【解决方案2】:

    我找到了解决方案。我使用 map 而不是 foreach 并且我删除了花括号并使用了常规的。

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

    【讨论】:

      【解决方案3】:

      您可以尝试使用 map 来代替 foreach 吗?例如

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

      【讨论】:

        猜你喜欢
        • 2021-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-02
        • 1970-01-01
        • 1970-01-01
        • 2021-02-18
        • 2021-10-11
        相关资源
        最近更新 更多