如何在reactjs中使用受保护的路由来保护我的页面

时间:2019-12-18 16:19:52

标签: reactjs react-router

我在reactjs中还很陌生,但是在reactjs中创建受保护的路由时遇到了麻烦。基本上,我只希望在授权路线后留下一页。我查看了tyler mcginnis指南,但我不太了解这一切,可能是因为仅当我拥有app.js,login.js和dashboard.js页面时,授权才在一页中完成,因此我很难尝试将指南中的点连接到我的项目中。如果有人可以帮助我,我将非常感激。我只希望我的仪表板页面在登录后。

App.js

import React, { useState } from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import "./App.css";
import Login from "./login";
import Dashboard from "./dashboard";
function App() {
  return (
    <>
      <Router>
        <div className="container">
          <nav className="navbar navbar-expand-lg navheader">
            <div className="collapse navbar-collapse">
              <ul className="navbar-nav mr-auto">
                <li className="nav-item">
                  <Link to={"/Login"} className="nav-link">
                    Login
                  </Link>
                </li>
              </ul>
            </div>
          </nav>
          <br />
          <Switch>
            <Route exact path="/login" component={Login} />
            <Route path="/dashboard" component={Dashboard} />
          </Switch>
        </div>
      </Router>
    </>
  );
}
export default App;

login.js

import React, { Component } from "react";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import AppBar from "material-ui/AppBar";
import RaisedButton from "material-ui/RaisedButton";
import TextField from "material-ui/TextField";
import { Link } from "react-router-dom";
import "./App";
class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: ""
    };
    this.onchange = this.onchange.bind(this);
  }
  onchange(e) {
    this.setState({ [e.target.name]: e.target.value });
  }
  performLogin = async () => {
    var body = {
      password: this.state.password,
      email: this.state.email
    };
    const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: JSON.stringify(body)
    };
    const url = "/api/authenticate";
    try {
      const response = await fetch(url, options);
      const text = await response.text();
      console.log(response.token);
      if (text === "redirect") {
        this.props.history.push(`/dashboard`);
      } else if (text === "verifyemail") {
        this.props.history.push(`/verifyOtp/${this.state.email}`);
      } else {
        console.log("login failed");
        window.alert("login failed");
      }
    } catch (error) {
      console.error(error);
    }
  };

  render() {
    return (
      <>
        <div className="loginForm">
          <MuiThemeProvider>
            <TextField
              hintText="Enter your Email"
              floatingLabelText="Email"
              onChange={(event, newValue) => this.setState({ email: newValue })}
            />
            <br />
            <TextField
              type="password"
              hintText="Enter your password"
              floatingLabelText="password"
              onChange={(event, newValue) =>
                this.setState({ password: newValue })
              }
            />
            <br />
            <RaisedButton
              label="Submit"
              primary={true}
              style={style}
              onClick={event => this.performLogin(event)}
            />
          </MuiThemeProvider>
        </div>
      </>
    );
  }
}
const style = {
  margin: 15
};
export default Login;

dashboard.js

import React, { Component } from "react";
import { Redirect, withRouter } from "react-router-dom";

class Dashboard extends Component {
  constructor(props) {
    super(props);
  }
  logout = () => {
     //not sure what to do here
  };
  render() {


    return (
      <>
        <div>hello</div>
        <button onCLick={this.logout}>Logout</button>
      </>
    );
  }
}
export default withRouter(Dashboard);

我不确定在哪里添加这些内容。就像我将它们添加到login.js中一样,那么我该如何更改道具,因为isAuthenticated将来自App.js,我认为是因为需要在更高的组件中声明状态,或者我误会了某些东西?

const fakeAuth = {
  isAuthenticated: false,
  authenticate(cb) {
    this.isAuthenticated = true
    setTimeout(cb, 100)
  },
  signout(cb) {
    this.isAuthenticated = false
    setTimeout(cb, 100)
  }
}

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
    fakeAuth.isAuthenticated === true
      ? <Component {...props} />
      : <Redirect to={{
          pathname: '/login',
          state: { from: props.location }
        }} />
  )} />
)

Codesandbox

0 个答案:

没有答案