【问题标题】:how can i prevent access to routes in react js我如何防止在反应 js 中访问路由
【发布时间】:2018-03-27 14:38:38
【问题描述】:

我正在使用 react-redux 更改我的应用程序中的状态。在我的路由器页面中,我如何根据条件进行路由。即,如果用户登录状态为真,那么如果我转到登录组件,它必须重定向到home 组件和用户登录状态为 false,如果我转到 home 组件,它必须重定向到 login 组件。

routes.js

const routes=() => (
    <Router>
        <div>
            <Header />
                <Route exact path="/" render={ props =>  <div><FirstConnectedComponent /><SecondConnectedComponent /></div>} />
                <Route path="/login" component={ requireAuth(Login) } />
                <Route path="/register" component={ UserReg } />
                <Route path="/home" component={ Home } />
            <Footer />
        </div>
    </Router>

)
export default routes;

【问题讨论】:

    标签: react-redux


    【解决方案1】:

    创建一个名为PrivateRoute的新路由组件怎么样

    PrivateRoute.js

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

    index.js

    先导入再使用 -

    <PrivateRoute path="/" component={MyComponent} />
    

    【讨论】:

      【解决方案2】:

      您可以添加函数调用: onEnter={this.requireAuth.bind(this)}

      函数可能是这样的:

      requireAuth(nextState, replace) {
          if (this.user === undefined || this.user === null) {
              replace('/login');
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2020-01-01
        • 1970-01-01
        • 2021-10-08
        • 2020-11-01
        • 2014-12-31
        • 1970-01-01
        • 1970-01-01
        • 2021-01-31
        • 1970-01-01
        相关资源
        最近更新 更多