【问题标题】:Account for null values when mapping an array ES6映射数组 ES6 时考虑空值
【发布时间】:2016-05-17 14:20:13
【问题描述】:

这是我正在成功映射一个数组..

const faculty = props.faculty;

{(faculty.science_department || []).map(science_dep => (
    <div className="row">
        <p>{science_dep.name} : {science_dep.start_date}</p>
    </div>
))}

但是如果数组是空的呢?我如何解释空值/空状态?如何在此地图功能中进行检查?即:显示

<p>There are no faculty members within this category</p>

【问题讨论】:

    标签: javascript arrays reactjs


    【解决方案1】:

    但是如果数组是空的呢?我怎样才能占空 值/空状态?如何在此地图功能中进行检查?即:显示

    <p>There are no faculty members within this category</p>
    

    考虑到这些要求,我将首先过滤数组,如果它包含任何内容,则使用地图渲染它,否则渲染占位符消息:

    const {faculty} = this.props;
    const science_department = (faculty.science_department || []).filter(dep => !!dep);
    
    { 
        science_department.length ? science_department.map(science_dep => (
            <div className="row" key={warning.id}>
                <p>{science_dep.name} : {science_dep.start_date}</p>
            </div>)
        : 
            <p>There are no faculty members within this category</p> 
    }
    

    PS:warning.id 是什么? key 应该是具有唯一值的 science_dep 的字段。

    【讨论】:

      【解决方案2】:

      假设您想在 JSX 语法中执行此操作,那么您可以使用 ternary operator:

      const faculty = props.faculty;
      
      {
        faculty.science_department.length !== 0 ?    
          faculty.science_department.map(science_dep => (
            <div className="row" key={warning.id}>
              <p>{science_dep.name} : {science_dep.start_date}</p>
            </div>
          ))
        :
          <p>There are no faculty members within this category</p>
      }
      

      【讨论】:

        【解决方案3】:
        {(faculty.science_department || []).length ? faculty.science_department.map(science_dep => (
        <div className="row" key={warning.id}>
            <p>{science_dep.name} : {science_dep.start_date}</p>
        </div>
        )) : (science_dep => (
        <div className="row" key={warning.id}>
            <p>There are no faculty members within this category</p>
        </div>)()}
        

        【讨论】:

        • 似乎抛出了关于&lt;/div&gt;)()}的意外令牌错误
        • 您想将“
          ...”分配给变量还是附加到 dom 元素?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-10
        • 1970-01-01
        • 2020-03-19
        • 2022-06-28
        • 2022-01-18
        • 2019-11-21
        相关资源
        最近更新 更多