简体   繁体   中英

Will having too many conditionals break a HOC in React?

I am trying to make a simple Higher Order Component in react. Its a supposed to render a <Link/> based on some props which I am using in conditionals to render my element.

I think the problem in one instance my desired result is a button which will render Log out if the isLoggedIn and the anchorText props are both false, and Log in if their true...

AND

I want that generic component to render an element isLoggedIn and the anchorText props are true and return nothing ie null if false...

Here it the HOC:

function GenericLoggedInLink({ isLoggedIn, logOutUser, route,anchorText }) {
 if ((isLoggedIn) && (anchorText === undefined)) {
  return <Link href="/"><a onClick={() => logOutUser()}>Log out!</a></Link>
 } else {
  return <Link href="/login"><a>Log in!</a></Link>
 }
 if ((isLoggedIn) && (anchorText)) {
 return <Menu.Item><Link href={route}><a>{anchorText}</a></Link></Menu.Item>
 } else {
  return null;
 }
}

And these are the Components being used;

<Menu.Item>
  <GenericLoggedInLink
    isLoggedIn={isLoggedIn}
    route="/profile"
    anchorText="Profile"
   />
   </Menu.Item>
   <Menu.Item>
    <GenericLoggedInLink
      isLoggedIn={isLoggedIn}
      route="/dashboard"
      anchorText="Dashboard"
     />
   </Menu.Item>

<Menu.Item position='right'>
  <Button inverted={!fixed}>
   <GenericLoggedInLink 
    isLoggedIn={isLoggedIn}    
    logOutUser={logOutUser}/>
 </Button>
</Menu.Item>

In VS code I actually get an error that the second conditional is unreachable? Can anyone help?

UPDATE

I tried what Cereal suggested, but now when the prop isLoggedIn === false the Log In is correct but the other links show this:

在此处输入图像描述

Your second conditional is unreachable.

In your first conditional, you always return from the function. If you're logged in and the anchor text is undefined, you return from the function. In all other cases you return from the function.

To fix this, you want to continue checking other conditions inside your else, essentially.

 if(isLoggedIn) {
   if(anchorText === undefined) {
     return <Link href="/"><a onClick={() => logOutUser()}>Log out!</a></Link>
   } else if(anchorText) {
     return <Menu.Item><Link href={route}><a>{anchorText}</a></Link></Menu.Item>
   } else {
     return null;
   }
 } else {
   return <Link href="/login"><a>Log in!</a></Link>
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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