Ram*_*gov 43 javascript ecmascript-6 reactjs redux react-redux
一切工作正常,但我有这个警告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
) // returnRun Code Online (Sandbox Code Playgroud)
Zan*_*non 83
A map()创建一个数组,因此return所有代码路径(if/elses)都需要a.
如果您不想要数组或返回数据,请forEach改用.
Kri*_*ekk 51
警告表示您在每种情况下都没有在地图箭头功能的末尾返回任何内容.
你想要完成的更好的方法是首先使用a .filter然后a .map,像这样:
this.props.comments
.filter(commentReply => commentReply.replyTo === comment.id)
.map((commentReply, idx) => <CommentItem key={idx} className="SubComment"/>);
Run Code Online (Sandbox Code Playgroud)
问题似乎是,如果您的首个if情况为假,则您没有返回任何内容。
您得到的错误表明您的arrow函数(comment) => {没有return语句。当if-case为true时会执行此操作,但为false时不会返回任何内容。
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.
}
});
Run Code Online (Sandbox Code Playgroud)
编辑您应该查看Kris的答案,以了解如何更好地实现您要尝试执行的操作。
来自 Kris Selbekk 的最受好评的答案是完全正确的。重要的是要强调它采用函数式方法,您将循环遍历this.props.comments数组两次,第二次(循环)它很可能会跳过一些过滤的元素,但如果没有comment被过滤,您将循环遍历整个阵列两次。如果您的项目不关心性能,那完全没问题。如果性能很重要,aguard clause会更合适,因为您只会循环数组一次:
return this.props.comments.map((comment) => {
if (!comment.hasComments) return null;
return (
<div key={comment.id}>
<CommentItem className="MainComment"/>
{this.props.comments.map(commentReply => {
if (commentReply.replyTo !== comment.id) return null;
return <CommentItem className="SubComment"/>
})}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
我指出这一点的主要原因是因为作为初级开发人员,我犯了很多这样的错误(比如多次循环同一个数组),所以我认为我在这里值得一提。
PS:我会重构你的反应成分就更多了,因为我赞成重逻辑的我不是html part的JSX,但就是这个问题的话题了。
| 归档时间: |
|
| 查看次数: |
62665 次 |
| 最近记录: |