简体   繁体   中英

Create a protected react route

I created a component that checks if the user is logged in, and if not it returns to the '/login' route. When testing the component, it returns the follow message:

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

This is my route

<Route exact path="/protected" render={ProtectedRoute}/>

the protected component

const ProtectedRoute = ( props ) =>
{
  return Sesion.IsUserLogged(props)
    .then( res =>
        {
        if(res)
        return <Redirect to="/login" />
        else
        return <h2>This is my protected route</h2>
        })
}

// Sesion script
class Session 
{
  IsUserLogged() 
  {
    let cookie = this.GetSessionCookie();

    if( cookie === undefined)
      return false;

    return this.ValidateUserSession(cookie);
  }


  ValidateUserSession(cookie)
  {

    return axios.post("http://localhost:3535/api/auth/validate", cookie)
      .then( function (res) 
          {
          return true;
          })
    .catch( function(err)
        {
        this.RemoveSessionCookies( );
        return false
        })
  }

  GetUserInfo()
  {  

    let cookie = this.GetSessionCookie();
    return axios.get(`http://localhost:3535/api/usrinfo/${cookie.UserID}`)
      .then( function (res) 
          {
          return res.data;
          })
    .catch( function(err)
        {
        if (err.response) 
        {
        return undefined;
        }
        })

  }

  RemoveSessionCookies( )
  {
    let COOKIE_NAME = Config.SesionCookieName;
    const cookie = new Cookies();
    cookie.remove(COOKIE_NAME);
  }

  GetSessionCookie()
  {
    let COOKIE_NAME = Config.SesionCookieName;
    const cookie = new Cookies();
    return cookie.get(COOKIE_NAME);
  }
}

Well, can anybody help me?

I think you can try this:

const ProtectedRoute = ( props ) => {
 const [isLogged, setIsLogged] = React.useState(false);
 const [isInitialized, setIsInitialized] = React.useState(false);



React.useEffect(() => { 
    if(!Sesion.IsUserLogged) {
        setIsLogged(false)
        setIsInitialized(true);
    }


    Sesion.IsUserLogged(props).then( res => {
        setIsLogged(!!res)
        setIsInitialized(true);
    });

    return () => {}
});

if(!isInitialized) {
    return null;
}

if(!isLogged) {
    return <Redirect to="/login" />
}

return (<h2>This is my protected route</h2>)
}

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