反应路由器v4身份验证不起作用

时间:2018-08-17 11:43:38

标签: reactjs firebase firebase-authentication react-router-v4

我对路由器身份验证有问题。我已经尝试在文档中使用该方法,但是它不起作用。

我计划在浏览器本地存储中保存我的用户登录状态。因此,当用户访问我的网站时。如果用户未登录,他们将被重定向到登录页面,成功登录后,我会将登录状态保存为localstorage并将用户重定向到网站。我还希望用户关闭标签页,然后再次访问网络,因为他们的状态仍处于登录状态,所以他们不再需要登录

现在的问题是

  1. 在初始状态下,我单击“登录”,页面将不会重定向,但是当我再次单击“登录”时,页面重定向

  2. 当我关闭选项卡并重新打开选项卡时。它将重定向到登录页面

这是代码:

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

class PrivateRoute extends React.Component {
  constructor(props) {
    super(props);
    this.state = { auth: ""  };
  }
  static getDerivedStateFromProps(props, state) {
    if (props.auth !== state.auth) {
      return {
        auth: props.auth
      };
    }
    return null;
  }
  componentDidMount = async () => {
    let auth = localStorage.getItem("signedIn");
    if (auth) this.setState({ auth: true });
  };
  render = () => {
    const { auth, component: Component, ...rest } = this.props;
    return (
      <Route
        {...rest}
        render={
          props => {
            if (this.state.auth) {
              return <Component {...props} />;
            } else {
              return (
                <Redirect
                  to={{
                    pathname: "/login",
                    state: { from: props.location }
                  }}
                />
              );
            }
          }
        }
      />
    );
  };
}

export default PrivateRoute;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

import React from "react";
const firebase = window.firebase;

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: "",
      password: ""
    };
  }
  login = async () => {
    await firebase
      .auth()
      .signInWithEmailAndPassword(this.state.username, this.state.password)
      .catch(function(error) {
        var errorMessage = error.message;
        // ...
        console.log("ERROR", errorMessage);
      });
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        localStorage.setItem("signedIn", "true");
        if (this.props.location.state.from !== "/login") {
          this.props.history.push(this.props.location.state.from.pathname);
        } else {
          this.props.history.push("/admin");
        }
      } else {
        console.log("no user signed in");
      }
    });
  };
}
export default withStyles(styles)(Login);

import React, { Component } from "react";
import Admin from "./components/Admin";
import Login from "./components/Login";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      auth: false
    };
  }
  componentDidMount = async () => {
    let auth = localStorage.getItem("signedIn");
    if (auth) {
      this.setState({ auth: true });
    } else {
      this.setState({ auth: false });
    }
  };

  render() {
    return (
      <MuiThemeProvider theme={myTheme}>
        <BrowserRouter>
          <div>
            <Route exact path="/" render={() => <Redirect to="/admin" />} />
            <Route path="/login" component={Login} />
            <PrivateRoute
              auth={this.state.auth}
              path="/admin"
              component={Admin}
            />
          </div>
        </BrowserRouter>
      </MuiThemeProvider>
    );
  }
}

export default App;

0 个答案:

没有答案