gpt4 book ai didi

javascript - 创建 protected react 路线

转载 作者:行者123 更新时间:2023-12-04 10:46:10 26 4
gpt4 key购买 nike

我创建了一个组件,用于检查用户是否已登录,如果未登录,则返回“/login”路由。测试组件时,它返回以下消息:

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.



这是我的路线

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

protected 组件

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

关于javascript - 创建 protected react 路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59696916/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com