条件语句未呈现else块

问题描述

在子组件Joke中,我具有以下条件渲染代码支持JSON文件的大多数笑话既有问题又有重点,但一个笑话只有一条要点。因此,如果存在一个问题,我希望同时显示问题和答案,否则,我将只显示突出显示线 并使用深红色:

function Joke(props) {
    if (props.question) {
    return (
        <div>
            <h3>Question: {props.question}</h3>
            <h3>Answer: {props.punchline}</h3>
            <hr />
        </div>
    )}
    else {
        return (
            <div>
                <h3 style={{color:"crimson"}}>{props.punchline}</h3>
                <hr />
            </div>
        )}
    }

export default Joke

现在实际输出的只是Question: and whatever the question isAnswer:,对于所有情况,答案均为空白。这种检查问题的条件逻辑是否正确?

解决方法

尝试下面的代码

function Joke(props) {
    return (
        <>
            {props?.question ? 
                          (<div>
                             <h3>Question: {props.question}</h3>
                             <h3>Answer: {props.punchline}</h3>
                             <hr />
                          </div>)
                          : (<div>
                               <h3 style={{color:"crimson"}}>{props.punchline}</h3>
                               <hr />
                             </div>)
                        }
            </>
       )
    }
,

我宁愿这样。

应用严格的检查并保留默认条件,以防万一没有满足条件。

db.collection("threads").aggregate([
  {
    $match: {
      _id: ObjectId(req.query.thread_id),},{
    $project: {
      _id: 1,date_created: 1,reverseMessages: {
        $slice: [
          { $reverseArray: "$messages" },parseInt(req.query.limit),// I guess you want to return latest n messages,where n is a limit from query
        ],]);