反应私人路线的高阶部分?

时间:2018-10-27 15:03:39

标签: reactjs

我正在尝试使PrivateRoute组件做出反应。这是我的高阶部分。你能告诉我这是什么问题吗?

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

export default ({ component: Component, ...rest }) => {
  class PrivateRoute extends React.Component {
    render() {
      console.log("This is private route called");
      if (this.props.profile) {
        return (
          <Route
            {...rest}
            render={props =>
              this.props.profile.loggedIn === true ? (
                <Component {...props} />
              ) : (
                <Redirect to="/login" />
              )
            }
          />
        );
      }
    }
  }

  const mapStateToProps = state => ({
    profile: state.profile
  });
  return connect(mapStateToProps)(PrivateRoute);
};

2 个答案:

答案 0 :(得分:2)

在这里,您可以通过受保护的路线组件来完成受保护的路线。

工作示例:https://codesandbox.io/s/yqo75n896x

容器/RequireAuth.js

import React from "react";
import { Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import ShowPlayerRoster from "../components/ShowPlayerRoster";
import ShowPlayerStats from "../components/ShowPlayerStats";
import Schedule from "../components/Schedule";

const RequireAuth = ({ match: { path }, isAuthenticated }) =>
  !isAuthenticated ? (
    <Redirect to="/signin" />
  ) : (
    <div>
      <Route exact path={`${path}/roster`} component={ShowPlayerRoster} />
      <Route path={`${path}/roster/:id`} component={ShowPlayerStats} />
      <Route path={`${path}/schedule`} component={Schedule} />
    </div>
  );

export default connect(state => ({
  isAuthenticated: state.auth.isAuthenticated
}))(RequireAuth);

routes / index.js

import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import { createStore } from "redux";
import { Provider } from "react-redux";
import Home from "../components/Home";
import Header from "../containers/Header";
import Info from "../components/Info";
import Sponsors from "../components/Sponsors";
import Signin from "../containers/Signin";
import RequireAuth from "../containers/RequireAuth";
import rootReducer from "../reducers";

const store = createStore(rootReducer);

export default () => (
  <Provider store={store}>
    <BrowserRouter>
      <div>
        <Header />
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/info" component={Info} />
          <Route path="/sponsors" component={Sponsors} />
          <Route path="/protected" component={RequireAuth} />
          <Route path="/signin" component={Signin} />
        </Switch>
      </div>
    </BrowserRouter>
  </Provider>
);

或者,如果您想要包裹所有路由的东西(而不需要指定受保护的路由组件)。然后,您可以执行以下操作。

工作示例:https://codesandbox.io/s/5m2690nn6n

components / RequireAuth.js

import React, { Component, Fragment } from "react";
import { withRouter } from "react-router-dom";
import Login from "./Login";
import Header from "./Header";

class RequireAuth extends Component {
  state = { isAuthenticated: false };

  componentDidMount = () => {
    if (!this.state.isAuthenticated) {
      this.props.history.push("/");
    }
  };

  componentDidUpdate = (prevProps, prevState) => {
    if (
      this.props.location.pathname !== prevProps.location.pathname &&
      !this.state.isAuthenticated
    ) {
      this.props.history.push("/");
    }
  };

  isAuthed = () => this.setState({ isAuthenticated: true });

  unAuth = () => this.setState({ isAuthenticated: false });

  render = () =>
    !this.state.isAuthenticated ? (
      <Login isAuthed={this.isAuthed} />
    ) : (
      <Fragment>
        <Header unAuth={this.unAuth} />
        {this.props.children}
      </Fragment>
    );
}

export default withRouter(RequireAuth);

routes / index.js

import React from "react";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import Home from "../components/Home";
import Players from "../components/Players";
import Schedule from "../components/Schedule";
import RequireAuth from "../components/RequireAuth";

export default () => (
  <BrowserRouter>
    <RequireAuth>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/players" component={Players} />
        <Route path="/schedule" component={Schedule} />
      </Switch>
    </RequireAuth>
  </BrowserRouter>
);

或者,如果您需要一些模块化的东西,可以在其中选择任意路线,则可以创建包装器HOC。请参阅此example(尽管它是为v3而编写的,而不是为身份验证而写的,但它仍然是相同的概念)。

答案 1 :(得分:0)

看起来您的渲染函数的唯一返回是在if块内部,因此它返回null。您需要修正逻辑以仅返回Route并将概要文件作为属性检查中的必需属性,而不是使用if块。

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