reactjs - 使用匿名函数进行条件渲染(React)
问题描述
我正试图了解条件渲染,并开始尝试使用匿名函数来实现这一点。
伪代码
if(statement)
render this
else
render something else
如果布尔值设置为 isLoggedin = true,则条件有效,但如果为 false,则抛出
Error: DisplayUserAcountDetails(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
我的实际代码
render() {
const isLoggedIn = false;
if (isLoggedIn)
return (
<div>
{(() => {
if (isLoggedIn) {
return (
<ul>
{this.state.AccountDetails &&
this.state.AccountDetails.map(function(
AccountDetails,
index
) {
return (
<div className="jumbotron">
<h3>Account Details</h3>
<li> Email: {AccountDetails.Email}</li>
<li> Name: {AccountDetails.NameOfUser}</li>
<li>
{" "}
Contact Number: {AccountDetails.ContactNumber}{" "}
</li>
<li>
<Link to="/profile-update-account-details">
<button>Update Account Details</button>
</Link>
</li>
</div>
);
})}
</ul>
);
} else {
return (
<div>
<div>otherCase</div>
<h1>Not there</h1>
</div>
);
}
})()}
</div>
);
}
为什么在渲染一个而另一个加载正常时会引发错误?是否有一些我遗漏的逻辑?
解决方案
1)您缺少 if else 语句的花括号 { }。
2)您应该检查 JavaScript 中的三元运算符。
推荐阅读
- javascript - 构建一个“可查询”的 javascript/JSON 对象
- algorithm - 您如何将 cronjob 编程为仅在上午 12 点和下午 12 点之后运行一次
- kotlin - 在 Kotlin 中选择属性初始化器和属性获取器的最佳实践是什么?
- python - 将复数的 numpy 矩阵导出到 CSV
- javascript - react-loadable / redux - 即使调用 createStore 也不会启动状态
- mongodb - Spring Boot Mongo DB 副本集未按预期工作
- rust - 为什么为无符号整数复制 C 的 fread 的通用函数总是返回零?
- javascript - 链接按钮到另一个页面
- sonarqube - 以下项目没有有效的 ProjectGuid 并且不是使用有效的解决方案 (.sln) 构建的,因此将从分析中跳过
- java - 在调用 OnClick 之前调用方法