简体   繁体   中英

why does my react header does not render at all?

So I have aa component called Header that will display a nav bar depending if a user is logged in or not, the props I am passing is a prop from the parent component that returns true as the user is already authenticated after login

App

 <Header IsLoggedIn={this.state.IsLoggedIn} />  

then this is my Header component that is not rendering

Header

// stateless functional component
import React from 'react';
import { NavLink } from 'react-router-dom'; //import Navlink to create nav links and to put active class on any link that is active
import UserGreeting from './UserGreeting'
import GuestGreeting from './GuestGreeting'
/*Header- Displays the top menu bar for the application and 
includes buttons for signing in and signing up 
(if there's not an authenticated user) or the user's first and last name 
and a button for signing out (if there's an authenticated user).*/


function Header(props) {
  const isLoggedIn = props;
  console.log(props)
  if (isLoggedIn ===true) {
    return <UserGreeting />;
  }
  else if(isLoggedIn===false) {
    return <GuestGreeting />;
  }
}

export default Header;

this is the error I get when I reload the page:

Uncaught Invariant Violation: Header(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null. Can someone help?

If isLoggedIn is undefined then isLoggedIn === false evaluates to false which causes your component to not return anything and results in the error you are seeing.


Change your else clause to this:

else {
  return <GuestGreeting />;
}

...or as @Isaac points out, remove the else completely and just do this:

if (isLoggedIn === true) {
  return <UserGreeting />;
}
return <GuestGreeting />;

...and that should fix it.


Ah, and @Jose is correct that you should use destructuring: const { isLoggedIn } = props; ...that is why isLoggedIn was undefined in the first place.

You should use es6 destructuring:

 const { isLoggedIn } = props; 

If you don't destructure your props, you're not getting the correct value from isLoggedIn so you don't return anything (thus the error).

Also don't need to check if false, just do:

 function Header(props) { const { isLoggedIn } = props; if (isLoggedIn) { return <UserGreeting />; } else { return <GuestGreeting />; } } 


TIP: You can do something like this for keeping your code tidy

 const Header = ({ isLoggedIn }) => isLoggedIn ? <UserGreeting /> : <GuestGreeting /> 

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