Reactjs 使用redux保护的路由和身份验证对路由器v4作出反应
我正在使用react路由器v4和redux,如果用户未登录,我想使用私有和受保护的路由重定向 我有一个路由组件:Reactjs 使用redux保护的路由和身份验证对路由器v4作出反应,reactjs,authentication,redux,react-router,react-router-v4,Reactjs,Authentication,Redux,React Router,React Router V4,我正在使用react路由器v4和redux,如果用户未登录,我想使用私有和受保护的路由重定向 我有一个路由组件: class Routes extends Component { render() { const { auth } = this.props; // so checks against isAuthenticated can pass if (auth.isAuthenticated !== undefined) { return (
class Routes extends Component {
render() {
const { auth } = this.props;
// so checks against isAuthenticated can pass
if (auth.isAuthenticated !== undefined) {
return (
<div>
<Route exact component={() => <Home />} />
<PublicRoute
authed={() => auth.isAuthenticated}
path="/login"
component={(routerProps) => <Login {...routerProps} />}
/>
<PublicRoute
authed={() => auth.isAuthenticated}
path="/register"
component={(routerProps) => <Register {...routerProps} />}
/>
<PrivateRoute
authed={() => auth.isAuthenticated}
path="/dashboard"
component={Dashboard}
/>
</div>
);
} else {
return <div></div>
}
}
}
function mapStateToProps(state) {
return {
auth: state.auth
}
}
export default withRouter(connect(mapStateToProps)(Routes));
类路由扩展组件{
render(){
const{auth}=this.props;
//因此,针对未验证的检查可以通过
如果(auth.isAuthenticated!==未定义){
返回(
} />
auth.isAuthenticated}
path=“/login”
组件={(路由程序=>}
/>
auth.isAuthenticated}
path=“/register”
组件={(路由程序=>}
/>
auth.isAuthenticated}
path=“/dashboard”
组件={Dashboard}
/>
);
}否则{
返回
}
}
}
函数MapStateTops(状态){
返回{
auth:state.auth
}
}
使用路由器导出默认值(连接(MapStateTops)(路由));
它是这样实现的:
class Main extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
store.dispatch(checkAuth());
}
render() {
return (
<Provider store={store}>
<Router>
<Theme>
<Routes />
</Theme>
</Router>
</Provider>
);
}
}
类主扩展组件{
建造师(道具){
超级(道具);
}
componentDidMount(){
store.dispatch(checkAuth());
}
render(){
返回(
);
}
}
这是私人路线:
export function PrivateRoute({ component: Component, authed, ...rest }) {
const isAuthenticated = authed();
return (
<Route
{...rest}
render={props =>
isAuthenticated === true ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
);
}
导出函数privaterout({component:component,authed,…rest}){
const isAuthenticated=authenticed();
返回(
isAuthenticated==真(
) : (
)
}
/>
);
}
传递
auth
prop的最佳方式是什么,如果我连接Routes组件并从那里传递auth
是否可以,或者应该从其他地方传递,或者连接需要它的每个组件并从那里读取?此外,这种方法如何处理嵌套路由,如/dashboard/settings
?谢谢实际上,在react中使用这种类型的专用路由是可以的,但您应该检查两个时刻:exact
属性,因此您的所有路线,如/dashboard/panel1
,/dashboard/panel2
,都是您的私人路线
auth.isAuthenticated}
path=“/dashboard”
组件={Dashboard}
/>如果家长不需要知道
PrivateRoute
的工作原理,您可以直接连接PrivateRoute
。@RobertFarley是的,我会试试,谢谢@RobertFarley但是如果你连接了很多PrivateRoute,你会有性能问题吗?谢谢,我不知道关于exact的事情,我会试试。对不起,我删除了你的答案,这里还是新的