【问题标题】:How do I correctly use a ternary operator in React如何在 React 中正确使用三元运算符
【发布时间】:2020-02-04 22:53:41
【问题描述】:

我正在从 API 获取数据,根据在我的网页上单击的项目,“描述”键中可能有也可能没有 JSON 数据。我正在尝试设置一个三元运算符,以便如果“描述”中存在数据,它应该显示该数据,如果没有,它应该显示“无描述”。当描述中有数据(条件为真)时,这一切都可以正常工作,但如果没有(条件为假),则分页符。

这个三元运算符不起作用有什么原因吗?

<div id="popup">
  <h2>{selectedEvent.name}</h2>
  {selectedEvent.descriptions[0].description ? (
  <p>{selectedEvent.descriptions[0].description}</p>
    ) : <p>No description</p>
}
</div>

谢谢

【问题讨论】:

  • 分页时,报错信息是什么?这是使用三元的正确方法,所以出现了其他问题。
  • 当条件为假时,您的 selectedEvent 对象是什么样子的?
  • 感谢大家的回复,我想通了。我只需要将条件更改为 - selectedEvent.descriptions[0] 删除 .description

标签: reactjs conditional-operator


【解决方案1】:

始终检查对象内的键

  const description = electedEvent.descriptions[0];
  return (
   <div id="popup">
    <h2>{selectedEvent.name}</h2>
     {description && description.description ? (
       <p>{description.description}</p>
     ) : <p>No description</p>
    }
   </div>
)

【讨论】:

    【解决方案2】:

    检查上面的这个例子:

     function getFee(isLoyalMember) {
          return (isLoyalMember ? '$2.00' : '$10.00'); // here the first output gets 
                                                      //returned if member is not 
                                                     //loyal. If customer is loyal, we 
                                                    //return $10.00 instead.
        }
    

    让我们通过控制台记录并查看输出:

        console.log(getFee(true));
        // expected output: "$2.00"
    
        console.log(getFee(false));
        // expected output: "$10.00"
    
        console.log(getFee(1));
        // expected output: "$2.00"
    

    让你的工作。执行以下操作:

      const description = electedEvent.descriptions[0];
      return (
       <div id="popup">
        <h2>{selectedEvent.name}</h2>
         {description && description.description ? (
           <p>{description.description}</p>
         ) : <p>No description</p>
        }
       </div>
    )
    

    【讨论】:

      猜你喜欢
      • 2014-06-18
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多