首页 > 解决方案 > 使用匿名函数进行条件渲染(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>
      );
  }

为什么在渲染一个而另一个加载正常时会引发错误?是否有一些我遗漏的逻辑?

标签: reactjs

解决方案


1)您缺少 if else 语句的花括号 { }。

2)您应该检查 JavaScript 中的三元运算符。


推荐阅读