javascript - 创建受保护的反应路线
问题描述
我创建了一个组件来检查用户是否登录,如果没有,它会返回到“/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>)
}
推荐阅读
- ios - 无法从此 NSManagedObjectContext 的协调器访问对象的持久存储
- vue.js - Vue test-utils 如何测试 router.push()
- java - 循环通过中等大小的数据集时 Kotlin 中的内存不足错误
- c - 从 C 数组中的 txt 文件第二行读取数字
- graylog - 基于字段值的 Graylog 警报条件
- azure - 无法部署到重新创建的已删除应用服务
- c++ - OpenGL:渲染天空盒立方体贴图问题
- unity3d - 统一使导弹遵循给定的轨迹
- android - ART 库在本机反应中不起作用
- css - Mailchimp 嵌入表单字体颜色