【问题标题】:Authentication for a reactjs application using two private routes使用两条私有路由对 reactjs 应用程序进行身份验证
【发布时间】:2018-11-04 12:21:44
【问题描述】:

我的 reactjs 应用程序有两种类型的用户,即艺术家和爱好者。我的一些组件只有艺术家可以访问,有些只有爱好者可以访问。所以我需要实现艺术家和用户路线,这将有助于只访问所需的用户类型。 这是我的路由器交换机

<Switch>
    <Route exact path='/' component={Home} />
    <UserRoute authed={this.state.lover} path='/user-dash' component={About} />
    <ArtistRoute authed={this.state.artist} path='/artist-dash' component={Contact} />
    <Route path='/SignupUser' component={SignupUser} />
</Switch>

这是我的 UserRoute 代码

import React from 'react';
import { Route, Redirect } from 'react-router-dom';
export const UserRoute = ({ component: Component, authed, ...rest }) => (
  <Route {...rest} render={props => (
        authed
        ? <Component {...props} />
        : <Redirect to={{ pathname: '/', state: { from: props.location } }} />
   )} />
)

我希望能够在交换机中传递的 UserRoute 中接收 authed 的值。我不知道为什么 UserRoute 中的 authed 总是返回 false。 即使 this.state.lover 传递给它也是如此。请问我做错了什么。 谢谢

【问题讨论】:

  • 你应该使用 HOC
  • @RaajNadar 有什么关于它的指令吗?或链接
  • @RaajNadar 正在使用 redux

标签: javascript reactjs


【解决方案1】:

Route.jsx

<Switch>
    <Route exact path='/' component={Home} />
    <Route path='/user-dash' component={AuthCheck(About)} /> // Wrap the component with HOC
</Switch>

AuthCheck.jsx

export default function(Component) {
    class AuthCheck extends Component {
        render() {
            if (this.props.auth.payload) {
                return <Component {...this.props} /> // Component if auth is true
            } else {
                return <Route path='*' exact={true} component={NotFound} /> // 404 if not auth
            }
        }
    }

    function mapStateToProps(state) {
        return { auth: state.auth }
    }

    return connect(mapStateToProps)(AuthCheck)
}

检查上面的例子是否适用于 redux

确保在 Route.jsx 文件中导入 AuthCheck

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2017-05-05
    • 2021-08-06
    • 2019-01-30
    • 2014-12-19
    相关资源
    最近更新 更多