首页 > 解决方案 > 验证完成后渲染私有路由不起作用

问题描述

我正在尝试设置私人路线。

这是我的 App.js 中的回报

      <Provider store={store}>
        <Router>
            <React.Suspense fallback={loading()}> 
                <Route exact path="/login" name="Login Page" render={props => <Login {...props}/>} />
                <Route exact path="/register" name="Register Page" render={props => <Register {...props}/>} />
                <Route exact path="/404" name="Page 404" render={props => <Page404 {...props}/>} />
                <Route exact path="/500" name="Page 500" render={props => <Page500 {...props}/>} />
                <Switch>
                  <PrivateRoute exact path="/" component={DefaultLayout} />
                </Switch>
            </React.Suspense>
        </Router>
      </Provider>

这是我的私有路由组件:

import React from "react";
import { Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";

const PrivateRoute = ({ component: Component, auth, ...rest }) => (
  <Route
  {...rest}
  render={props =>
    auth.isAuthenticated === true ? (
      <Component {...props} />
      ) : (
        <Redirect to="/login" />
      )
    }
    />
);

PrivateRoute.propTypes = {
  auth: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  auth: state.auth
});

export default connect(mapStateToProps)(PrivateRoute);

我认为问题出在 auth.isAuthenticated; 当我将其更改为 true === true 时,正确的组件--DefaultLayout--按设计呈现。

但是,当我 console.log(this.props.auth) 时,我收到一个错误,指出 this.props.auth 未定义。

编辑: 当我将组件重写为基于类的组件和渲染部分中的 console.log 时,我收到了道具。所以,我相信我收到了道具,还有另一个问题。

我知道组件发生了什么:组件和 ...rest,但我认为我不知道当它被传递到私有路由时,身份验证到底发生了什么。

我知道 this.props.auth 存在,因为当我在我的登录组件中 console.log 时,我可以看到用户已登录并获得授权。

标签: reactjsreact-router

解决方案


试试这个,而不是:

<Switch>
  <PrivateRoute exact path="/" component={DefaultLayout} />
</Switch>

删除Switch包装 的组件PrivateRoute,它可以防止 store 传递给您的PrivateRoute

应用程序.js:

      <Provider store={store}>
        <Router>
            <React.Suspense fallback={loading()}> 
                <Route exact path="/login" name="Login Page" render={props => <Login {...props}/>} />
                <Route exact path="/register" name="Register Page" render={props => <Register {...props}/>} />
                <Route exact path="/404" name="Page 404" render={props => <Page404 {...props}/>} />
                <Route exact path="/500" name="Page 500" render={props => <Page500 {...props}/>} />
                <PrivateRoute exact path="/" component={DefaultLayout} />
            </React.Suspense>
        </Router>
      </Provider>

推荐阅读