简体   繁体   English

条件渲染未显示 - ReactJS

[英]Conditional rendering not displaying - ReactJS

I have a log out button that I only want to show when the user is logged in. 我有一个注销按钮,我只想在用户登录时显示。

I have created a function for this purpose and included the function in the return part of react but it's not working. 我已经为此创建了一个函数,并将函数包含在react的返回部分中,但它不起作用。

This is the function: 这是功能:

const ifloggedin = () => {
    if (!localStorage.hasOwnProperty('token')) {
      return null
} else {
return <li><a href="#contact" className="Contact" onClick={logout} to={"/"}>Log Out</a></li>
}
  }

This is how I am trying to render it in return: 这就是我试图渲染它的方式:

        <div className="content">
          <li><a href="#hiw" className="Hiw" to={"/about"}>HOW IT WORKS</a></li>
          <li><a href="#pricing" className="Price" to={"/pricing"}>PRICING</a></li>
          <li><Link className="Faq" to={"/Faq"}>FAQ</Link></li>
          <li><a href="#contact" className="Contact" to={"/contact"}>CONTACT</a></li>
          {ifloggedin}
        </div>

ifloggedin is a function so you need to call it. ifloggedin是一个函数,所以你需要调用它。

 <div className="content">
          <li><a href="#hiw" className="Hiw" to={"/about"}>HOW IT WORKS</a></li>
          <li><a href="#pricing" className="Price" to={"/pricing"}>PRICING</a></li>
          <li><Link className="Faq" to={"/Faq"}>FAQ</Link></li>
          <li><a href="#contact" className="Contact" to={"/contact"}>CONTACT</a></li>
          {ifloggedin()}
</div>

You have to call ifloggedin as ifloggedin(), because it is an arrow function. 你必须将ifloggedin称为ifloggedin(),因为它是一个箭头函数。 But in your case you are using it for conditional rendering so no need to write arrow function for that. 但在你的情况下,你正在使用它进行条件渲染,所以不需要为此编写箭头函数。

You can write it as normal function and use as ifloggedin() 您可以将其写为普通函数并使用ifloggedin()

 ifloggedin() {
if (!localStorage.hasOwnProperty('token')) {
  return null;
} else {
  return (
    <li>
      <a href="#contact" className="Contact" onClick={logout} to={'/'}>
        Log Out
      </a>
    </li>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM