首页 > 解决方案 > 使用单个三元运算符渲染多个组件

问题描述

如果currentProfiles.length > 0,我想映射一个名为 profiles 的数组并为每个配置文件呈现一个配置文件组件,在配置文件下方呈现一个分页组件。我用一个三元运算符尝试了这个,但这只会导致分页组件被渲染。

    {currentProfiles.length > 0 ? (
      (currentProfiles.map(profile => (
        <ProfileItem key={profile._id} profile={profile} />
      )),
      (
        <Pagination
          profilesPerPage={profilesPerPage}
          totalProfiles={profiles.length}
        />
      ))
    ) : (
      <Spinner />
    )}

如果我使用两个单独的三元运算符,我会得到预期的配置文件列表和分页,但是我可以用一个条件运算符来做这两件事吗?

标签: javascriptreactjs

解决方案


您的代码只需要一些重组。如果您将映射的配置文件和分页组件包装在父片段或其他元素中,这很容易。另请注意,下面的第一个示例仍按要求保留三元组。

  return (
    <div className="App">
      {currentProfiles.length ? (
        <>
          {currentProfiles.map(p => (
            <Profile {...p} />
          ))}
          <Pagination profilesPerPage={2} totalProfiles={totalProfiles} />
        </>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );

但是,除了将它们包装在非渲染Fragment或其简写派生中之外,您还有一些选择。您还可以使用实际元素,例如div. 或者甚至完全省略父级并将您的逻辑放在一个数组中,如下所示:

<div className="App">
  {currentProfiles.length ? [
    currentProfiles.map(p => (
      <Profile {...p} />
    )),
    <Pagination profilesPerPage={2} totalProfiles={totalProfiles} />
  ] : <p>Loading...</p>}
</div>

永远记住,除非你使用第二种方法,否则你需要确保兄弟姐妹有一个共同的父母。

工作示例


推荐阅读