【问题标题】:How to handle 3 different conditions in a React function component如何在 React 函数组件中处理 3 种不同的条件
【发布时间】:2022-01-16 00:49:03
【问题描述】:

我正在渲染一个帖子列表。这些帖子将显示 3 种不同类型的内容。所以所有这些帖子的列表视图都是一样的。标准标题、缩略图、作者等。但是当您转到这 3 种不同类型的页面时,内容会呈现不同的布局(不同的组件)。我有一个简单的三元运算符来为两种链接类型设置不同的链接。但是现在我有 3 个设置该逻辑的最佳实践是什么?

这是我目前所拥有的:

 <div className="all-posts">
                    { currentPosts?.map(post => (
                        <Link key={post.id} className="link-wrapper" to={post.course_trailer ? `course/${post.id}` : `/lesson/${post.id}`}> 
                            <div  className="post-container">
                                <div className="thumbnail-container">
                                 <img className="post-thumbnail" src={post.course_trailer ? post.featured_image : post.app_thumbnail} alt="" />
                                </div>
                                <div className="post-meta">
                                    <p className="post-title">{post.title}</p>
                                    <div className="author-meta">
                                        <div className="author-container">
                                            <p className="post-teacher">@{post.instructor_name}</p>
                                            <img className="verification-badge" src="#" alt="" />
                                        </div>
                                        <p className="post-views">Views: {post.views}</p>
                                    </div>
                                </div>
                            </div>           
                        </Link>
                    ))
                    }  
    </div>

您在 Link 中看到我有三元组。现在我需要设置逻辑,如 if post.course_trailer go to this path if post.formulas then go to this path else go to the标准路径。

【问题讨论】:

  • 你可以有一个嵌套的十进制来添加第三种情况。例如参考这个链接:stackoverflow.com/questions/10526739/…
  • 您不必使用三元组(尽管您可以像foo ? "do foo" : (bar ? "do bar" : "do quux") 一样嵌套它们)。为什么不把它分解成一个函数,把你用英文写的if-else变成代码呢?我不确定“这条路径”和“标准路径”是什么意思,所以除了“这是一个通用的嵌套三元组”之外,很难写出答案。

标签: javascript reactjs


【解决方案1】:

在保持三元理智的同时解决此问题的一种方法(我喜欢称其为 :D)是将逻辑提取到函数中。让我们将其命名为getLinkForPost。该函数获取一个作为参数传递的post对象,并返回对应的字符串。

const getLinkForPost(post) => {
   if(post.course_trailer) return 'path1';
   if(post.formulas) return 'path2';
   return 'default path';
}
...
//somewhere in render
<Link key={post.id} className="link-wrapper" to={getLinkForPost(post)}> 
...

【讨论】:

    【解决方案2】:

    您可以无限嵌套三元组。

    function component (){
        return (
            <div>
                {post.course_trailer
                    ? `course/${post.id}`
                    : post.formulas ? `/lesson/${post.id}` : `/standard`
                }
            </div>
        );
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-22
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      • 2022-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      相关资源
      最近更新 更多