簡體   English   中英

創建受保護的反應路線

[英]Create a protected react route

我創建了一個組件,用於檢查用戶是否已登錄,如果未登錄,則返回“/login”路由。 測試組件時,它返回以下消息:

錯誤:對象作為 React 子對象無效(找到:[object Promise])。 如果您打算渲染一組子項,請改用數組。

這是我的路線

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

受保護的組件

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);
  }
}

嗯,有人可以幫我嗎?

我想你可以試試這個:

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>)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM