2016-12-15 62 views
1

剛開始看reactjsx並嘗試檢查一個數組(this.state.content)是否爲未定義和長度> 0。這是渲染方法的一部分:如何檢查reactjsx中的條件?

display = (
     <section> 
      { 
       if (this.state.content.length >0) 
       { 
       this.state.content.map((item, i) => { 
        return <CardRenderer addPacks={true} key={i} container={item}/> 
       }) 
       } 
      } 
     </section> 
    ) 

然而,這並不工作,我怎樣才能在jsx中首先檢查這個arraylength?

回答

1

嘗試:

display = (
     <section> 
       { 
       this.state.content && this.state.content.map((item, i) => { 
        return <CardRenderer addPacks={true} key={i} container={item}/> 
       }) 
      } 
     </section> 
    ) 

&&將短路地圖如果this.state.content未定義,並且如果this.state.content具有零的長度,地圖將什麼也不做(但不會有一個錯誤)。

0

您可以使用三元運算符

display = (
     <section> 
      { 
       (this.state.content && this.state.content.length > 0)? 
       { 
       this.state.content.map((item, i) => { 
        return <CardRenderer addPacks={true} key={i} container={item}/> 
       }) 
       } : null 
      } 
     </section> 
    )