reactjs - 验证完成后渲染私有路由不起作用
问题描述
我正在尝试设置私人路线。
这是我的 App.js 中的回报
<Provider store={store}>
<Router>
<React.Suspense fallback={loading()}>
<Route exact path="/login" name="Login Page" render={props => <Login {...props}/>} />
<Route exact path="/register" name="Register Page" render={props => <Register {...props}/>} />
<Route exact path="/404" name="Page 404" render={props => <Page404 {...props}/>} />
<Route exact path="/500" name="Page 500" render={props => <Page500 {...props}/>} />
<Switch>
<PrivateRoute exact path="/" component={DefaultLayout} />
</Switch>
</React.Suspense>
</Router>
</Provider>
这是我的私有路由组件:
import React from "react";
import { Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
const PrivateRoute = ({ component: Component, auth, ...rest }) => (
<Route
{...rest}
render={props =>
auth.isAuthenticated === true ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
PrivateRoute.propTypes = {
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(mapStateToProps)(PrivateRoute);
我认为问题出在 auth.isAuthenticated; 当我将其更改为 true === true 时,正确的组件--DefaultLayout--按设计呈现。
但是,当我 console.log(this.props.auth) 时,我收到一个错误,指出 this.props.auth 未定义。
编辑: 当我将组件重写为基于类的组件和渲染部分中的 console.log 时,我收到了道具。所以,我相信我收到了道具,还有另一个问题。
我知道组件发生了什么:组件和 ...rest,但我认为我不知道当它被传递到私有路由时,身份验证到底发生了什么。
我知道 this.props.auth 存在,因为当我在我的登录组件中 console.log 时,我可以看到用户已登录并获得授权。
解决方案
试试这个,而不是:
<Switch>
<PrivateRoute exact path="/" component={DefaultLayout} />
</Switch>
删除Switch
包装 的组件PrivateRoute
,它可以防止 store 传递给您的PrivateRoute
:
应用程序.js:
<Provider store={store}>
<Router>
<React.Suspense fallback={loading()}>
<Route exact path="/login" name="Login Page" render={props => <Login {...props}/>} />
<Route exact path="/register" name="Register Page" render={props => <Register {...props}/>} />
<Route exact path="/404" name="Page 404" render={props => <Page404 {...props}/>} />
<Route exact path="/500" name="Page 500" render={props => <Page500 {...props}/>} />
<PrivateRoute exact path="/" component={DefaultLayout} />
</React.Suspense>
</Router>
</Provider>
推荐阅读
- python - aiokafka:在考虑 kafka 的消费者组重新平衡时处理消息需要锁定
- java - 完全透明的观察者
- c - 如何在 C 中创建地图?
- angular - Angular 库链接到 Angular 项目,但面临意外值错误
- sql-server - LINQ to Entity with left join
- google-analytics - 如何在测量协议 api 中发送基本地理数据?
- visual-studio-code - 我应该如何取消 jupyer notebook 中单元格的执行
当我运行一个单元格然后我想停止执行时,我不知道该怎么做:在 google collab 上,有一个小停止按钮,我们必须单击它来停止单元格(它会引发键盘中断)。在 Vscode 上,我发现了这个红色方块,但只有当我单击单元格顶部的“按行运行”时,这不是我想要做的......我发现这样做的唯一方法是杀死整个内核这也不是一个好主意
有没有办法停止单元格的
- ambari - 我们可以为上传/下载目的实现自定义 ambari 操作吗
- excel - Laravel ajax 返回 excel 而不是二进制字符串
- android - 如何从材料设计主题中删除操作栏高度?