2017-07-10 30 views
9

一切工作正常,但我有這個警告Expected to return a value at the end of arrow function array-callback-return,我嘗試使用forEach而不是map,但然後<CommentItem />甚至沒有顯示。如何解決它?預計在箭頭函數結束時返回一個值

return this.props.comments.map((comment) => { 
 
    
 
     if (comment.hasComments === true) { 
 
     
 
     return (
 
      <div key={comment.id}> 
 
      
 
      <CommentItem className="MainComment"/> 
 

 
       {this.props.comments.map(commentReply => { 
 
       
 
       if (commentReply.replyTo === comment.id) { 
 
        return (
 
        <CommentItem className="SubComment"/> 
 
       ) // returnt 
 
       } // if-statement 
 
       }) // map-function 
 
       } // map-function __begin 
 
      
 
      </div> // comment.id 
 
      
 
     ) // return

+0

如果您不進入if,是否還有其他回報? – epascarello

+2

只有'commentReply.replyTo === comment.id'時纔會返回。如果情況並非如此,你什麼都不會回來。只要在'if'塊後面加上'return null' –

+0

Mikael Lennholm,我想說,你是天才 –

回答

15

的警告表明你沒有在你的地圖箭頭功能在任何情況下最終返回的東西。

一個更好的辦法來你想要什麼來完成第一次使用.filter然後.map,像這樣:

this.props.comments 
    .filter(commentReply => commentReply.replyTo === comment.id) 
    .map((commentReply, idx) => <CommentItem key={idx} className="SubComment"/>); 
2

的問題似乎是,你是不是在事件返回的東西,你的第一個if-案件是假的。

您收到的錯誤表明您的箭頭功能(comment) => {沒有返回語句。雖然它適用於您的if -case爲真的情況,但它在錯誤時不會返回任何內容。

return this.props.comments.map((comment) => { 
    if (comment.hasComments === true) { 
    return (
     <div key={comment.id}> 
     <CommentItem className="MainComment" /> 
     {this.props.comments.map(commentReply => { 
      if (commentReply.replyTo === comment.id) { 
      return (
       <CommentItem className="SubComment"/> 
      ) 
      } 
     }) 
     } 
     </div> 
    ) 
    } else { 
    //return something here. 
    } 
}); 

編輯你應該看看克里斯的回答如何更好地實施你正在嘗試做的。

1

A map()創建一個數組,因此預計所有代碼路徑return(如果/ elses)。

如果您不想要數組或返回數據,請改爲使用forEach

相關問題