reactjs - 如何使用 ReactJS 组件添加用户身份验证
问题描述
我想实现基于 ReactJS 组件的用户身份验证。我是 ReactJS 的新手,它是一个团队软件项目,所以我们不使用 webhook,而是使用组件。身份验证本身正在工作,但不是内容之后的呈现。
在 app.js 文件中,我使用条件渲染来显示内容或登录页面:
if (this.getToken('token') === null || this.getToken('token') === undefined) {
shownComponent = <LoginComponent token={this.state.token} setToken={this.setToken} />;
} else {
shownComponent = <MainComponent />;
}
在 LoginComponent 中,我实现了以下逻辑:
registerUser = () => {
const data = {
userName: this.state.userName,
userPassword: this.state.userPassword
}
return fetch('/users/createUser', {
method: 'post',
mode: 'cors',
headers:{
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Accept': 'application/json'
},
body: JSON.stringify(data),
})
.then((data) => {
if(data.status === 200){
console.log('User has been stored to database');
return true
}
})
.catch((error) => console.log( error.response.request) );
}
loginUser = () => {
return fetch('/login',{ headers:{
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Accept': 'application/json'
} })
.then((response) =>{
return response.json();
})
.then((data) =>{
return data;
});
}
login = async () => {
this.setState({loggedin: true})
const registered = await this.registerUser()
const userToken = await this.loginUser();
this.props.setToken(userToken)
}
从登录表单调用登录功能后(不是复制粘贴在这里),它只会重新呈现登录页面,但不会重定向回 app.js 并现在呈现主要内容。
解决方案
推荐阅读
- javascript - 我正在尝试使用 puppeteer 在页面上自动登录,一旦我在下一页上登录,我想单击下一页上的按钮
- java - 转换为浮点数/从浮点数转换时 BigDecimal 不保留舍入值
- html - Angular Material:自动缩放元素的高度
- ansible - Ansible - vmware_guest 模块创建 windows 服务器机器
- python - 我如何使用移动平均线的定义,编写 Python 代码(使用 for 循环)来计算一个称为 ma 的 n 周期移动平均线列表?
- javascript - DateTimePicker 的问题以及如何将所选日期传递给另一个函数?
- decentralized-identity - 如何确保可验证的凭证颁发者是合法的颁发者?
- python - Django models.TextChoices 不可索引?
- r - 将 FlexTable 中的数字与 R 中的十进制数字对齐
- postgresql - 有没有办法检查一列是否在 postgresql 中具有正确的日期格式?