reactjs - React JS make async call without componentdidmount()
问题描述
I'm trying to do an API call triggered only when the user clicks on the submit button
This is in a user login context where the parent's component state gets changed.
import React from 'react';
import {Button, FormGroup, FormControl, ControlLabel} from "react-bootstrap";
import './login.css';
export default class loginForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
answer:[],
};
this.handleSubmit = this.handleSubmit.bind(this);
}
async handleSubmit(event) {
const jso = JSON.stringify({
username: this.state.username,
password: this.state.password
})
const response = await fetch("https://app.herokuapp.com/authentication", {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: jso,
})
const json = await response.json()
this.setState({answer:json});
//check if user is authentificated
alert("Server Answer : "+ this.state.answer.answer);
if(this.state.answer.answer.localeCompare('true') == 0){
this.props.app.setState({auth: true});
sessionStorage.setItem('auth', true);
}
else if (this.state.username != ""){
alert("INCORRECT USERNAME PASSWORD ");
}
}
render() {
return (<div className="Login">
<form onSubmit={this.handleSubmit}>
//part omitted because not relevant for this question
<Button bsSize="small" color="primary" type="submit">
Login
</Button >
</form>
</div>)
}
}
My question: Is it possible to do something like this or I absolutely need to use componentDidMount()
?
I've been struggling / searching about this for too much time now and I still can't find a way to make it work.
解决方案
有可能做到这一点。据我所知,一旦到达//check if user is authentificated
. 发生这种情况是因为 reactsetState
是异步的。
为了在修改后立即访问状态,该setState
函数采用可选的回调函数,因此您可以尝试编写如下代码:
this.setState({answer:json}, () => {
//check if user is authentificated
alert("Server Answer : "+ this.state.answer.answer);
if(this.state.answer.answer.localeCompare('true') == 0){
this.props.app.setState({auth: true});
sessionStorage.setItem('auth', true);
}
else if (this.state.username != ""){
alert("INCORRECT USERNAME PASSWORD ");
}
});
推荐阅读
- delphi - 以管理员身份运行会阻止 DropTarget 的 onDropped
- racket - 如何修复我的吹嘘/球拍解析器中的未绑定标识符错误?
- python-3.x - 为什么我的 ML 模型的准确性很差?
- java - 谷歌片段 getSignInIntent() 返回 RESULT_CANCELED
- node.js - 如何使用测试笑话覆盖依赖于节点环境的条件
- android - SQLite 多查询 - 提高性能的最佳设计方法
- wpf - WPF 任意角度旋转并返回 BitmapSource
- indexing - 为配置集配置 solr 索引/存储属性
- c# - 在 Unity 中制作无尽的环视觉效果
- jquery - 动态检测输入文本中的填充信息