reactjs - 如何使用 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])。如果您打算渲染一组子项,请改用数组。
我知道这是因为它返回了一个承诺,但我正在等待它,但它没有像我认为的那样工作,有什么原因吗?.
解决方案
将您的私有路由组件更改为以下内容:
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" />
)
}
/>
)
}
推荐阅读
- facebook-opengraph - Facebook 无法识别的打开图形属性
- r - mc.cores = 1 的 mclapply() 是否与 lapply() 相同?
- amazon-ec2 - kubernetes 的高磁盘使用率(IOPS 和带宽)
- sqlite - SQLite 中的日期时间转换
- objective-c - presentViewControllerAsSheet OSX 的完成处理程序
- c# - 如何让游戏中的物体更好地移动
- javascript - Django/Plotly - 带有 JS 的点击事件
- oracle - 通过使用 Oracle 的 Join 获取每个状态的 Store 计数
- cmake - How to print without newline in CMake?
- javascript - 根据我的下拉选择在我的文本框中填充 Db 值