限制导航以防止浏览器挂在React App中

时间:2019-06-19 12:04:02

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

我正在从React中进行登录/注册,并且正在使用firebase auth进行身份验证。用户登录后,我想在根路径或App组件上重定向用户。但是我陷入了一个无限循环,这给了我这个错误(限制导航以防止浏览器挂起。)

    import React, { useEffect } from "react";
    import ReactDOM from "react-dom";
    import "semantic-ui-css/semantic.min.css";
    import App from "./App";
    import firebase from "firebase";
    import { BrowserRouter, Switch, Route, withRouter } from "react- 
router-dom";
    import Login from "./components/Login";
    import Register from "./components/Register";

    const Root = props => {
      useEffect(() => {
        firebase.auth().onAuthStateChanged(user => {
          if (user) {
            props.history.push("/");
          }
        });
      });
      return (
        <Switch>
          <Route exact path="/" component={App} />
          <Route path="/login" component={Login} />
          <Route path="/register" component={Register} />
        </Switch>
      );
    };

    const RootWithAuth = withRouter(Root);

    ReactDOM.render(
      <BrowserRouter>
        <RootWithAuth />{" "}
      </BrowserRouter>,
      document.getElementById("root")
    );

1 个答案:

答案 0 :(得分:2)

您的问题来自React,在useEfect中:

  

如果您熟悉React类的生命周期方法,可以考虑   useEffect Hook作为componentDidMount,componentDidUpdate和   componentWillUnmount组合。

您的无限循环是因为您当前还将useEfect用作componentDidUpdate,只需在useEfect的末尾添加[],这将导致useEfect充当componentDidMount。

useEffect(() => {
        firebase.auth().onAuthStateChanged(user => {
          if (user) {
            props.history.push("/");
          }
        });
      }, []);