[英]Two map statement within one return with if array contains items from another array
我正在构建一个简单的博客应用程序,我正在尝试检查博客是否在喜欢的博客数组中,以返回 function。 所以我创建了two array
,一个是all blogs
,另一个是liked blogs
,我试图显示“喜欢博客”的消息但是 return 语句中的two map
函数显示意外结果或显示奇怪的多个结果。
应用程序.js
class Blogs extends React.Component {
const all_blogs = [
{"blog_title" : "First Blog"},
{"blog_title" : "Second Blog"},
{"blog_title" : "Third Blog"},
{"blog_title" : "Fourth Blog"},
{"blog_title" : "Fifth Blog"},
]
const liked_blogs = [
{"blog_title" : "Second Blog"},
{"blog_title" : "Third Blog"},
]
render() {
return (
<div>
{
all_blogs.map(blog =>
liked_blogs.map(liked_blog => {
if (blog.blog_title === liked_blog.blog_title) {
return (
<div>This blog is liked</div>
)
} else {
<div>This blog is NOT liked</div>
}
}
}
</div>
)
}
}
我正在尝试检查all_blogs
博客是否在liked_blogs
中喜欢或不喜欢,如果喜欢博客,则显示返回div
,如果没有,则显示其他div
我已经尝试了很多次,但它仍然无法正常工作。
嵌套的 map 将return
多维数组,这不会是 output 预期的结果,您需要通过some
方法查找blog
是否存在于linked_blogs
中,然后有条件地显示该消息。
class Blogs extends React.Component { const all_blogs = [ {"blog_title": "First Blog"}, {"blog_title": "Second Blog"}, {"blog_title": "Third Blog"}, {"blog_title": "Fourth Blog"}, {"blog_title": "Fifth Blog"}, ] const liked_blogs = [ {"blog_title": "Second Blog"}, {"blog_title": "Third Blog"}, ] render() { return ( <div> { all_blogs.map(blog => liked_blogs.some(liked_blog => blog.blog_title === liked_blog.blog_title)? <div>This blog is liked</div>: <div>This blog is NOT liked</div>) } </div> ) } }
您绝对应该使用字典,如下所示;
const all_blogs = [
{"blog_title" : "First Blog"},
{"blog_title" : "Second Blog"},
{"blog_title" : "Third Blog"},
{"blog_title" : "Fourth Blog"},
{"blog_title" : "Fifth Blog"},
]
const liked_blogs = {
"Second Blog": true,
"Third Blog": true,
}
const innerContent = all_blogs.map(blog => liked_blogs[blog.blog_title] // this prevents inner loop and runs at O(1)
? <div>This blog is liked</div>
: <div>This blog is NOT liked</div>)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.