reactjs - 反应路由器私有路由/重定向不适用于 redux
问题描述
我正在尝试设置受保护的路由,如果用户没有登录,他们将被重定向到 /login 页面,但在使用 redux 时它不起作用。
这是我的 ProtectedRoute 组件:
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Route, Redirect } from 'react-router-dom';
import { authenticate } from './actions';
const ProtectedRoute = ({
component: Component, authenticate, isAuthenticated, ...rest
}) => {
useEffect(() => {
authenticate();
});
return (
<Route
{...rest}
render={props => (isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to="/login" />
))
}
/>
);
};
ProtectedRoute.propTypes = {
component: PropTypes.elementType.isRequired,
authenticate: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
};
const mapStateToProps = state => ({
isAuthenticated: state.isAuthenticated,
});
const mapDispatchToProps = {
authenticate,
};
export default connect(mapStateToProps, mapDispatchToProps)(ProtectedRoute);
这是路线:
<Provider store={store}>
<Router>
<Switch>
<ProtectedRoute exact path="/" component={App} />
<Route path="/login" component={LoginPage} />
</Switch>
</Router>
</Provider>
现在,在您将其标记为重复之前,我已经尝试了其他线程中的解决方案。
使用withRouter
不起作用。
withRouter(connect(mapStateToProps, mapDispatchToProps)(ProtectedRoute))
同样的事情{pure: false}
connect(mapStateToProps, mapDispatchToProps, null, {pure: false})(ProtectedRoute);
我也用Switch
. 我不知道如何让它工作。
解决方案
为什么不使用 HOC 组件来检查身份验证?
import React, { Component } from 'react';
import { connect } from 'react-redux';
export default ChildComponent => {
class ComposedComponent extends Component {
componentDidMount() {
this.shouldNavigateAway();
}
componentDidUpdate() {
this.shouldNavigateAway();
}
shouldNavigateAway() {
if (!this.props.auth) {
this.props.history.push('/');
}
}
render() {
return <ChildComponent {...this.props} />;
}
}
function mapStateToProps(state) {
return { auth: state.auth.authenticated };
}
return connect(mapStateToProps)(ComposedComponent);
};
现在你只需要将这个组件导入到受保护的组件中,然后像下面这样导出受保护的组件,
import authCheck from 'blah/blah...'
export default authCheck(ProtectedComponent)
推荐阅读
- javascript - Vue 2 和 Typescript:将任何道具传递给自定义组件时出现 VS 代码错误 TS2769
- python - 汇总数据以计算组合的出现次数
- reactjs - React + Apollo 客户端:usequery 结合加载和“加载”状态
- visual-studio-code - 你能“分叉”一个 VS Code 扩展或让扩展一起工作吗?
- php - laravel 微风的问题
- reactjs - React-Redux:getState() 不可用
- authentication - 为什么禁用港口身份验证模式?
- angular - 组件上未检测到 NGXS 更新状态
- node.js - 当我单击客户端站点时,显示此错误
- binary - 如何使用 zmq c++ 发送二进制数据