【问题标题】:React router v4 authentication issue反应路由器 v4 身份验证问题
【发布时间】:2017-10-25 13:42:49
【问题描述】:

我正在尝试在我的 react 应用程序中创建基本身份验证流程。

我正在使用 redux 和 redux-persist 将我的状态存储到本地存储中。

这是一个PrivateRoute 组件,用于检查用户身份验证然后重定向到登录或实际组件(这是私有的)。

authenticated 设置为 false 时,它​​工作正常。但是当我成功登录时,即使我的authenticated 是真的,它也不会呈现我的组件。 (我记录了变量,我看到验证是真的,登录成功)

import React from 'react';
import PropTypes from 'prop-types';
import { Route } from 'react-router';
import { Redirect } from 'react-router-dom';
import { isAuth } from 'redux/actions/auth/A_auth';
import App from 'layout/pages/App';
import { connect } from 'react-redux';

class PrivateRoute extends React.Component {

   constructor(props) {
      super(props);
   }

   render() {
      const {authenticated, component: Component, ...rest } = this.props;
      console.log(this.props);
      return (
         <Route {...rest} render={props => (
            authenticated ? (
               <App>
                  <Component {...props}/>
               </App>
            ) : (
               <Redirect to={{
                  pathname: '/login',
                  state: { from: props.location }
               }}/>
            )
         )}/>
      );
   }
}

PrivateRoute.propTypes = {
   authenticated: PropTypes.bool
};

const mapStateToProps = state => {
   return {
      authenticated: state.auth.authenticated
   }
};

export default connect(mapStateToProps)(PrivateRoute);

authenticated == false 它重定向到Login.js 但当它的true它不呈现实际组件。当我删除 if 语句并仅渲染 &lt;App&gt;&lt;Component.../&gt;&lt;/App 时,它工作正常,但在这种情况下身份验证不起作用。

这是我的 index.js,它是根渲染。

render(
<Provider store={store}>
  <Router children={routes}/>
</Provider>, window.document.getElementById('app'));

这是我的 routes.js

import React from 'react';
import { Route } from 'react-router-dom';
import Home from 'layout/pages/home';
import NewClient from 'layout/pages/newclient';
import EditClient from 'layout/pages/editclient';
import Login from 'layout/pages/login';
import PrivateRoute from 'routes/PrivateRoute';

export default (
   <div>
      <PrivateRoute path="/" component={Home} exact/>
      <PrivateRoute path="/home" component={Home} exact/>
      <PrivateRoute path="/client/new" component={NewClient}/>
      <PrivateRoute path="/client/edit/:apiKey" component={EditClient}/>
      <Route path="/login" component={Login}/>
   </div>
);

谢谢。

【问题讨论】:

    标签: reactjs authentication redux react-router-v4


    【解决方案1】:

    解决了。

    我改变了这个

    <Redirect to={{ pathname: '/login', state: { from: props.location } }}/>

    到这里

    &lt;Login/&gt;

    重定向组件导致问题还是不知道为什么。

    【讨论】:

      猜你喜欢
      • 2017-09-26
      • 2018-12-19
      • 2018-05-21
      • 1970-01-01
      • 2017-09-24
      • 2018-05-16
      • 2018-07-07
      • 1970-01-01
      • 2015-11-30
      相关资源
      最近更新 更多