2017-08-22 84 views
2

我想有條件地在我的頁面上顯示幾條消息。以下是我的實際場景的簡化代碼。有條件的渲染與三元運算符在反應

<div> 
    { 
     isCondition1 == true ? 
      'Show issue list' 
     : 
      isConditionA == true? 
       'Show message for condition A' 
      : 
       'Show error message' 
    } 
</div> 
<div> 
    { 
     isCondition2 == true? 
      'Show team issue list' 
     : 
      isConditionA == true? 
       'Show message for condition A' 
      : 
       'Show error message' 
    } 
</div> 

我想從上面拿出常見的東西,並在代碼中使用它。

const msgNoIssues = (
    isConditionA == true? 
     'Show message for condition A' 
    : 
     'Show error message' 
); 

而且按如下方式使用它:

<div> 
    { 
     isCondition1 == true? 
      'Show issue list' 
     : 
      {msgNoIssues} 
    } 
</div> 
<div> 
    { 
     isCondition2 == true ? 
      'Show team issue list' 
     : 
      {msgNoIssues} 
    } 
</div> 

但它給了一個錯誤信息:

Objects are not valid as a React child (found: object with keys {msgNoIssues}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.

能把它沒有反應插件可以實現嗎?有沒有更好的方法來做到這一點?

回答

1

When {} is needed in JSX?

我們需要使用{}把裏面JSX JS表達,所以就把三元運營商內部{}

Reason of this error: Objects are not valid as a React child

{ msgNoIssues }含義是{ msgNoIssues: msgNoIssues }這意味着你試圖渲染與關鍵msgNoIssues的對象,這就是爲什麼它被拋出的錯誤:對象是不是有效的做出反應的孩子(發現:與鍵{msgNoIssues}對象)。

解決方案:

刪除{}msgNoIssues四周,這樣寫:

<div> 
    { 
     isCondition1 == true ? 
      'Show issue list' 
     : 
      msgNoIssues 
    } 
</div> 
<div> 
    { 
     isCondition2 == true ? 
      'Show team issue list' 
     : 
      msgNoIssues 
    } 
</div> 

檢查這個片段(的{ a }意思):

let a = 10; 
 

 
let obj = {a}; 
 

 
console.log('obj = ', obj);

檢查DOC:Embedding Expressions in JSXConditional Rendering