reactjs - React Router - 身份验证检查呈现空白页面
问题描述
我对 React Router 还很陌生。当应用程序运行时,我正在尝试实施身份验证检查:如何在 React Router 4 中实现经过身份验证的路由?. 如果登录它应该加载仪表板组件,如果没有,你应该被重定向到登录屏幕。
重定向不起作用,它只是一个空白页面。
有任何想法吗?
export default class App extends React.Component {
state = {
auth: false
};
updateAuth = value => {
this.setState({
auth: value
});
};
render() {
const { auth } = this.state;
console.log(auth);
const PrivateRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={props =>
auth ? (
<Component {...rest} />
) : (
<Redirect
to={{ pathname: "/login", state: { from: props.location } }}
/>
)
}
/>
);
};
return (
<Router>
<div>
<Route path="/login" component={Login} auth={this.updateAuth} />
<PrivateRoute path="/dashboard" component={Dashboard} />
</div>
</Router>
);
}
}
解决方案
您仍然path
将 PrivateRoute 上的属性设置为/dashboard
,如果您转到https://qlj5rnnlnq.codesandbox.io/dashboard,它将尝试加载您的仪表板页面,但由于服务器上的文件没有 . .js 文件扩展名。
如果要从根 URL 转到仪表板页面,请将路径更改为:
<PrivateRoute authed={true} path="/" component={Dashboard} />
并更改仪表板文件上的文件扩展名,使其变为Dashboard.js
推荐阅读
- python - 通过删除布局框架从 QGridLayout 中删除小部件
- javascript - 如何在 Vuejs 中使用 axios 获取下载文件(.xlsx)?
- rest - 如何在express中使用rest api
- github - 按文件名及其文件内容搜索 Github 存储库
- plsql - 从通过 oracle 过程调用的 REST API 的响应中提取特定组件
- ios - 将标签的高度放在堆栈视图中的 UIView 内时表现异常
- node.js - 为什么postgres查询总是为主键返回null?
- python - 训练具有多个公共输出的 tensorflow 模型
- ruby-on-rails - Elatic Beanstalk Worker 和 Elastic Beanstal Rails API 如何协同工作?
- c# - 使用 System.Text.Json 反序列化 Json 时间戳