【发布时间】:2021-11-18 11:17:50
【问题描述】:
我使用这种方法向用户显示私人页面。问题是没有向我显示任何页面,但我放入 PrivatePage 的日志可以正常工作。
Components 是正确的,因为当我简单地调用路由时,组件会正确返回,但是 PrivatePage 有问题并且什么都不做。
错误文本:
错误:对象作为 React 子对象无效(找到:[object 承诺])。如果您打算渲染一组孩子,请使用 代替数组。
在用户访问某个地址之前,我必须通过服务器验证该用户,因为用户使用该站点有时间限制,所以我使用了Promise。
function Auth() {
return new Promise((resolve, reject) => {
let appData = GetAppData();
if (appData.UserToken.length == 0) {
reject(-2);
}
let request = {
Token: appData.UserToken,
UserId: appData.UserId
}
axios.post("****UserValidUrl****", request).then(response => {
switch (response.data.Type) {
case 10:
resolve(10);
break;
case -2:
reject(-2);
break;
case -13:
reject(-13);
}
}).catch(err => {
reject(-13);
})
})
}
私人页面:
const PrivatePage = ({children, ...rest}) => (
return <Route
{...rest}
render={async ({location }) => {
let type = 10;
try {
type = await Auth();
} catch(e) {
type = -13;
}
Log(type);
switch (type) {
case 10:
return children;
break
case -2:
return (
<Redirect
to={{
pathname: '/Auth/Login',
state: { from: location },
}}
/>)
case -13:
return (
<Redirect
to={{
pathname: '/NotFound',
state: { from: location },
}}
/>)
break;
}}
}/>
)
基本页面:
export default function BasePage() {
return (
<div>
<BrowserRouter>
<Switch>
<Route exact path={"/Auth/Login"} component={Login}/>
<PrivatePage path={"/"}>
<Switch>
<Route exact path={"/"} component={Home}/>
<Route exact path={"/Dashboard/Home"} component={Home}/>
<Route exact path={"/Dashboard/Profile"} component={Profile}/>
<Route component={NotFound}/>
</Switch>
}/>
</Switch>
</BrowserRouter>
</div>
);
}
【问题讨论】:
标签: reactjs authentication routes react-router jsx