2017-06-02 47 views
2

我想在我的陣營組件添加內嵌有條件的,但我不明白爲什麼,陣營返回意外的令牌,預計上線posts.length ?陣營內聯有條件返回意外的令牌,預計

class PostList extends Component { 

    getPosts() { 
    const posts = Post.find().fetch(); 
    return posts; 
    } 

    render() { 
    const posts = this.getPosts(); 
    return (
     {posts.length ? 
     <ul> 
      {posts.map((post) => (
      <PostItem key={post.title} post={post} /> 
     ))} 
     </ul> 
     } 
    ); 
    } 

} 

任何人有想法?我的條件是錯誤的?

謝謝社區!

+2

是的,你的條件是錯誤的:三元表達式必須同時擁有''部分和':'一部分,你不能刪除一個表達式爲'{}'對象初始化就像那樣。 – Pointy

+0

你有沒有試過使用額外的? 。 '{posts.length ??' – Ollie

+0

@Ollie:這不是有效的語法,是嗎?我從來沒有在JavaScript中見過''',只有在C#中。 –

回答

4

返回null當表達式的計算結果爲false。也不要使用{},使用此()

class PostList extends React.Component { 
 
    
 
     getPosts() { 
 
     //const posts = Post.find().fetch(); 
 
     const posts = ["post1","post2"] 
 
     return posts; 
 
     } 
 
    
 
     render() { 
 
     const posts = this.getPosts(); 
 
     return (
 
      posts.length ? 
 
       <ul> 
 
       {posts.map((post) => (
 
        <PostItem key={post.title} post={post} /> 
 
       ))} 
 
       </ul>: 
 
       null 
 
     ) 
 
     } 
 
    
 
    } 
 
    
 
    class PostItem extends React.Component{ 
 
    render(){ 
 
     return (<div>{this.props.post}</div>) 
 
    } 
 
} 
 

 
ReactDOM.render(<PostList />, document.getElementById("app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="app"></div>

+2

我認爲'{}'應該仍然會導致錯誤。 – Pointy

+0

@Pointy查看更新的答案。 – nrgwsth

+0

謝謝@anuragasaurus,它工作很好! –

1

下面是anuragasaurus答案稍有語法變化。

如果在您的情況下沒有「其他」,則不需要三元表達condition ? value1 : value2。您可以改用Short-circuit evaluation

由於邏輯表達式是從左向右計算,他們正在使用以下規則測試 可能的「短路」的評價:

  • false && (anything)是短路評估爲錯誤。
  • true || (anything)被短路評估爲真。

邏輯規則 保證這些評估總是正確的。請注意,上述表達式的任何部分都不會被評估,因此這樣做的任何一方都不會生效。還要注意,上述表達式的任何部分 是任何單個邏輯表達式(如圓括號所示的 )。


class PostList extends Component { 

    getPosts() { 
    const posts = Post.find().fetch(); 
    return posts; 
    } 

    render() { 
    const posts = this.getPosts(); 
    return (
     posts.length && 
     <ul> 
      {posts.map((post) => <PostItem key={post.title} post={post} />)} 
     </ul> 
    ); 
    }  
} 
+0

它仍然會給出錯誤。您需要將代碼包裝在「div」塊中。這樣組件在某些情況下不會返回'null'。 – nrgwsth

+0

@anuragasaurus,我不這麼認爲。組件可以返回null或false。 – Chris

+2

@Chris刪除'{}周圍'{posts.length && .... }'應該是'return(posts.length && .... )' –