javascript - 使用单个三元运算符渲染多个组件
问题描述
如果currentProfiles.length > 0
,我想映射一个名为 profiles 的数组并为每个配置文件呈现一个配置文件组件,并在配置文件下方呈现一个分页组件。我用一个三元运算符尝试了这个,但这只会导致分页组件被渲染。
{currentProfiles.length > 0 ? (
(currentProfiles.map(profile => (
<ProfileItem key={profile._id} profile={profile} />
)),
(
<Pagination
profilesPerPage={profilesPerPage}
totalProfiles={profiles.length}
/>
))
) : (
<Spinner />
)}
如果我使用两个单独的三元运算符,我会得到预期的配置文件列表和分页,但是我可以用一个条件运算符来做这两件事吗?
解决方案
您的代码只需要一些重组。如果您将映射的配置文件和分页组件包装在父片段或其他元素中,这很容易。另请注意,下面的第一个示例仍按要求保留三元组。
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>
永远记住,除非你使用第二种方法,否则你需要确保兄弟姐妹有一个共同的父母。
工作示例。
推荐阅读
- python - Python:使用来自其他函数的 WITH(上下文管理器)
- c# - 在 selenium C# 中处理表
- java - JAVA:使用 swagger.v3.parser.OpenAPI 解析 OPEN API
- react-native - fetch 无法从 json 服务器 API 端点获取响应
- r - 我们可以使用 as.factor 将具有多个级别的分类变量转换为决策树还是我们需要使用 model.matrix?
- java - 无法使用 igniterealtime/REST-API-Client 在 openfire 创建用户
- android - 安卓计费库V3.0.0 不工作
- java - 使用 Firebase 计算用户之间的位置
- python - BERT 服务器未启动
- java - JAVA-SPRING - 错误 java.lang.ClassNotFoundException: "com.mysql.jdbc.Driver" 将我的连接连接到其他类但在 Main 上工作