首页 > 解决方案 > 如何使用 react-router-dom amplify 保护或验证 React 路由

问题描述

我正在使用 React 和 amplify 构建一个应用程序。身份验证和授权可以正常工作。但它需要限制用户在登录应用程序之前移动到某些特定的 React 路由。以下代码片段是我尝试过的,如果isAuthenticated()返回 false,它会起作用。但是由于我使用 Amplify 我使用一种方法

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={async props =>
      await isAuthenticated() ? (
        <Navigation>
          <Component {...props} />
        </Navigation>
      ) : (
        <Redirect to="/login" />
      )
    }
  />
);

这是我的 isAuthenticated() 函数的代码。

import Auth from "@aws-amplify/auth";
export const isAuthenticated = async () => {
  try {
    return await Auth.currentSession().isValid();
  } catch (error) {
    return false;
  }
};

但这会引发这样的错误。

错误:对象作为 React 子项无效(找到:[object Promise])。如果您打算渲染一组子项,请改用数组。

我知道这是因为它返回了一个承诺,但我正在等待它,但它没有像我认为的那样工作,有什么原因吗?.

标签: reactjsreact-router-domaws-amplify

解决方案


将您的私有路由组件更改为以下内容:

const PrivateRoute = ({ component: Component, ...rest }) => {
  const [isLoggedIn, setIsLoggedIn] = useState(false)
  useEffect(async () => {
    const isAuth = await isAuthenticated()
    setIsLoggedIn(isAuth)
  }, [])
  return (
    <Route
      {...rest}
      render={props =>
        isLoggedIn ? (
          <Navigation>
            <Component {...props} />
          </Navigation>
        ) : (
            <Redirect to="/login" />
          )
      }
    />
  )
}

推荐阅读