【问题标题】:React ternary operator with array.map return用 array.map 返回反应三元运算符
【发布时间】:2018-01-26 21:59:49
【问题描述】:

在我的 react 渲染函数中,我使用 array.map 在数组中返回一些 JSX 代码,然后渲染它。这似乎不起作用,我在这里阅读了一些建议在 if/else 块中使用 return 语句的问题,但这在我的情况下不起作用。我想检查是否在每个数组元素上设置了轮次和持续时间,然后才将其传递给 JSX 代码。请有人告诉我不同​​的方法。

render() {
 var interviewProcessMapped = interviewProcess.map((item, index) => {

  return
    {item.round ?
        <div className="row title">
          <div className="__section--left"><span className="section-title">Round {index + 1}</span></div>
          <div className="__section--right">
            <h3>{item.round}</h3>
          </div>
        </div>
        : null
    }

    {
      item.durationHours > 0 || item.durationMinutes > 0 ?
        <div className="row">
          <div className="__section--left">Duration</div>
          <div className="__section--right border">
            {item.durationHours > 0 ? <span>{item.durationHours} Hours</span> : null} {item.durationMinutes > 0 ? <span>{item.durationMinutes} Minutes</span> : null}
          </div>
        </div>
        : null
    }
  });

 return <div>{interviewProcessMapped}</div>
}

【问题讨论】:

  • 在两个对象之间添加,?喜欢,而不是return { } { },试试return ( { } , { } )
  • @JeremyThille 似乎不起作用。
  • 您的函数有 a) 在 return 之后的换行符 b) 两个返回语句 c) 在纯 JS 表达式中它们不属于的大括号(不像在 JSX 文字中它们是必要的)

标签: javascript arrays reactjs


【解决方案1】:

{ 这里不需要:

return {item.round ?

如果你使用它,这意味着你正在返回一个对象。

另一个问题是单独的return 表示return; (automatic semicolon insertion) 所以要么将条件放在同一行,要么使用()

这样写:

render() {
    let a, b;
    var interviewProcessMapped = interviewProcess.map((item, index) => {
        a = item.round ?
                <div className="row title">
                    ....
                </div>
            : null;

        b =  (item.durationHours > 0 || item.durationMinutes > 0) ?
                  <div className="row">
                      ....
                  </div>
              : null;

        if(!a || !b)
            return a || b;
        return [a, b];
    });

    return (....)
}

【讨论】:

  • 这只会返回 item.round 的 div(如果存在),如果在被映射的数组中提供了相应的数据,我希望返回所有 div
  • @ManavSaxena 检查更新的答案,抱歉错过了那部分:)
【解决方案2】:

您可能应该结合使用 Array.prototype.map() 和 Array.prototype.filter()

根本不需要if

这里是伪代码:

interviewProcess.filter(() => {
    // return only if round and duration set
}).map(() => {
    // transform the filtered list
});

【讨论】:

    猜你喜欢
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 2018-04-11
    • 1970-01-01
    • 2018-07-24
    • 2019-07-19
    相关资源
    最近更新 更多