使用aws-amplify作为身份验证的PrivateRoute功能组件

时间:2020-03-28 16:27:59

标签: javascript reactjs react-router aws-amplify

我正在尝试创建与以下PrivateRoute类组件(源代码here)等效的功能组件:

import React, { useState, useEffect } from "react";
import { Route, Redirect, withRouter, useHistory } from "react-router-dom";
import { Auth } from "aws-amplify";

class PrivateRoute extends React.Component {
  state = {
    loaded: false,
    isAuthenticated: false
  };
  componentDidMount() {
    this.authenticate();
    this.unlisten = this.props.history.listen(() => {
      Auth.currentAuthenticatedUser()
        .then(user => console.log("user: ", user))
        .catch(() => {
          if (this.state.isAuthenticated)
            this.setState({ isAuthenticated: false });
        });
    });
  }
  componentWillUnmount() {
    this.unlisten();
  }
  authenticate() {
    Auth.currentAuthenticatedUser()
      .then(() => {
        this.setState({ loaded: true, isAuthenticated: true });
      })
      .catch(() => this.props.history.push("/auth"));
  }
  render() {
    const { component: Component, ...rest } = this.props;
    const { loaded, isAuthenticated } = this.state;
    if (!loaded) return null;
    return (
      <Route
        {...rest}
        render={props => {
          return isAuthenticated ? (
            <Component {...props} />
          ) : (
            <Redirect
              to={{
                pathname: "/auth"
              }}
            />
          );
        }}
      />
    );
  }
}

export default withRouter(PrivateRoute);

当我这样使用时,上面的代码在我的应用程序中起作用:

<PrivateRoute
  exact
  path={urls.homepage}
  component={Homepage}
/>

我将上述类组件转换为功能组件的尝试如下:

import React, { useState, useEffect } from "react";
import { Route, Redirect, useHistory } from "react-router-dom";
import { Auth } from "aws-amplify";

const PrivateRoute = ({ component: Component, ...rest }) => {
  const [isLoaded, setIsLoaded] = useState(false);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  let history = useHistory();

  useEffect(() => {
    Auth.currentAuthenticatedUser()
      .then(() => {
        setIsLoaded(true);
        setIsAuthenticated(true);
      })
      .catch(() => history.push("/auth"));

    return () =>
      history.listen(() => {
        Auth.currentAuthenticatedUser()
          .then(user => console.log("user: ", user))
          .catch(() => {
            if (isAuthenticated) setIsAuthenticated(false);
          });
      });
  }, [history, isAuthenticated]);

  if (!isLoaded) return null;

  return (
    <Route
      {...rest}
      render={props => {
        return isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/auth"
            }}
          />
        );
      }}
    />
  );
};

export default PrivateRoute;

但是当以相同的方式使用我的功能组件时,我不断收到以下错误:

警告:无法在已卸载的组件上执行React状态更新。这是空操作,但它表明应用程序中发生内存泄漏。要修复,请取消使用useEffect清理功能中的所有订阅和异步任务

它始终将我重定向到/ auth,无论是否登录。我究竟做错了什么?任何帮助深表感谢!

2 个答案:

答案 0 :(得分:1)

我认为您错过了卸载,useEffect 中的返回应该是您的 unlisten,即卸载。此外,我删除了 useHistory 并从道具中拉出 history 并使用了 withRouter

试试这个

import React, { useState, useEffect } from "react";
import { Route, Redirect, withRouter } from "react-router-dom";
import { Auth } from "aws-amplify";

const PrivateRoute = ({ component: Component, history, ...rest }) => {
  const [isLoaded, setIsLoaded] = useState(false);
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  useEffect(() => {
    Auth.currentAuthenticatedUser()
      .then(() => {
        setIsLoaded(true);
        setIsAuthenticated(true);
      })
      .catch(() => history.push("/auth"));
    
    const unlisten = history.listen(() => {
      Auth.currentAuthenticatedUser()
        .then(user => console.log("user: ", user))
        .catch(() => {
          if (isAuthenticated) setIsAuthenticated(false);
        });
    });

    return unlisten();
  }, [history, isAuthenticated]);

  if (!isLoaded) return null;

  return (
    <Route
      {...rest}
      render={props => {
        return isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/auth"
            }}
          />
        );
      }}
    />
  );
};

export default withRouter(PrivateRoute);

答案 1 :(得分:0)

尝试一下:

useEffect(() => {
  async function CheckAuth() {
    await Auth.currentAuthenticatedUser()
      .then((user) => {
        setIsLoaded(true);
        setIsAuthenticated(true);
      })
    .catch(() => history.push("/auth"));
  }
  CheckAuth();
}, []);