javascript - 登录/注册 AWS Cognito React 的安全页面
问题描述
我正在为应用程序创建登录/注册页面,并且我是第一次使用 AWS Cognito 和 React。在有人登录/注册之前,我需要保护我的页面。我不知道如何将 userAuth() 中的任何内容发送到导出默认值,或者如何使其工作。
import React, { Component } from 'react';
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
withRouter
} from 'react-router-dom';
import App from '../App';
import { Auth } from 'aws-amplify';
//last thing 333
async function userAuth() {
let something = Boolean;
Auth.currentSession()
.then(function(fulfilled) {
console.log('worked' + fulfilled);
something === true;
return something;
})
.catch(function(error) {
console.log('didnt work' + error);
window.location.href = '/';
return error;
});
}
export default ({ component: C, ...rest }) => (
alert('this is the user auth ' + userAuth()),
(
<Route
{...rest}
render={
props =>
userAuth() === 'something' ? (
<Redirect to="/" />
) : (
<C {...props} />
)
}
/>
)
);
解决方案
Auth.currentAuthenticatedUser()
是一个异步 API,所以你不能从这个 API 返回任何可以在 a 中使用的东西Route
(有可能返回 a Promise
,但这实际上不是必需的。)
您可以将组件更改为class
类似:
class PrivateRoute extends React.Component {
constructor(props) {
super(props);
this.state = {
authStatus: false,
loading: false,
}
}
componentDidMount() {
Auth.currentAuthenticatedUser()
.then((user)=> {
this.setState({ loading: false, authStatus: true });
})
.catch(() => {
this.setState({ loading: false });
this.props.history.push('/login');
});
}
render() {
return <Route {...rest} render={(props) => (
this.state.authStatus
? <Component {...props} />
: <div>Loading ... </div>
)} />
}
}
推荐阅读
- xml - XSLT 从 XMLNS/XML 获取正确的 GUID
- c# - 将数据从 WinForms 发送到网站数据库
- postgresql - 如何在 gorm many2many 关联中仅获取 ID 列表
- java - 使用 openfeign 的多个表单数据
- loopback4 - loopback 4 legacy juggler replaceById 和 updateById 将不需要的 id 字段添加到 mongodb 中的嵌入文档
- python - python数据类没有属性post_init
- mysql - 如何在mysql中生成季度报告并按一年中的每个季度汇总
- ios - Swift / HTTPS - 收到无效的标头 HTTP 标头字段
- amazon-web-services - longhorn 和 ebs 以及自动缩放组
- android - google maps on android 9 crash “Failed resolution of: Lorg/apache/http/ProtocolVersion”