首页 > 解决方案 > React-Redux:如果用户未登录,则限制用户访问某些页面的最佳方法

问题描述

我是 React/Redux 的新手,我正在开发一个 React 应用程序。我一直在学习 Redux 的基本概念,例如 Store、Actions、Reducers、Middleware 和 connect() 函数。

但是,对于我的应用程序中的某些页面,我希望只允许登录的用户能够访问它们,否则它们将被重定向回应用程序的主页。

我想知道能够完成这项任务的最佳方法是什么?我听说可以使用 React Router 来做到这一点,但是有没有更好的方法呢?任何见解都值得赞赏。

标签: javascriptreactjsredux

解决方案


正如您已经建议的路由器,使用它可以安全地使用它,假设用户仅设置为 redux 状态,当在登录中正确验证时:

import { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom':

const mapStateToProps = (state) => {
    return {
        user: state.user
    }
}

class MyPageWrapper extends Component {

    componentWillMount() {
        if(!this.props.user) this.props.history.push('/login');
    }

    render() {
        return (
            <div>
                <YourPage/>
            </div>
        );
    }
}

export default connect(mapStateToProps)(withRouter(MyPageWrapper));

推荐阅读